I would like to split strings on the first and last comma. Each string has at least two commas. Below is an example data set and the desired result.
A similar ques
Here is a relatively simple approach. In the first line we use sub
to replace the first and last commas with semicolons producing s
. Then we read s
using sep=";"
and finally cbind
the rest of my.data
to it:
s <- sub(",(.*),", ";\\1;", my.data[[1]])
DF <- read.table(text=s, sep =";", col.names=paste0("mystring",1:3), as.is=TRUE)
cbind(DF, my.data[-1])
giving:
mystring1 mystring2 mystring3 some.data
1 123 34,56,78 90 10
2 87 65,43 21 20
3 a4 b6 c8888 30
4 11 bbbb ccccc 40
5 uu vv,ww xx 50
6 j k,l,m,n,o p 60