rstring

Apply string split into list


I have the following string:

exm<-"c(1,2,3),c(4,5),c(7,8,9),c(10,11)"

I need to convert this into a list with vectors with 3 or 2 elements (according with the string), so far by now my code worked:

res<-eval(parse(text=paste("list(",exm,")",sep="")))

But recently Power Bi throws an error in this section and don't let me use eval/parse anymore, how could I replace it (using base r)? I am trying with gsub and lapply but can't find propper documentation.


Solution

  • if you can't use your eval + parse, you can start with sth like

    lapply(strsplit(gsub("c\\(|\\(|\\)","",strsplit(exm, ",c")[[1]]), ","), as.numeric)
    
    [[1]]
    [1] 1 2 3
    
    [[2]]
    [1] 4 5
    
    [[3]]
    [1] 7 8 9
    
    [[4]]
    [1] 10 11
    
    1. splits the string by ,c into "c(1,2,3)" "(4,5)" "(7,8,9)" "(10,11)"
    2. gsub("c\\(|\\(|\\)","",x[[1]]) removes brackets and c "1,2,3" "4,5" "7,8,9" "10,11"
    3. strsplit(x,"c") splits x2 into a list (of characters)
    4. lapply applies as.numeric to all list-items to make them numeric

    or more robust against spaces in between vectors

    lapply(strsplit(gsub("c\\(|\\(|\\)", "", regmatches(exm, gregexpr("c\\([^)]+\\)", exm))[[1]]), ","), as.numeric)
    

    Notes