Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Apply string split into list

Tags:

string

r

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.

like image 892
David Ricardo Menacho Vadillo Avatar asked Dec 02 '25 01:12

David Ricardo Menacho Vadillo


1 Answers

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

  • assuming your vectors in c are numeric and they follow the shown structure, if they are not numeric, leave away the lapply
like image 87
Tim G Avatar answered Dec 03 '25 16:12

Tim G



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!