split strings on first and last commas

后端 未结 5 1933
生来不讨喜
生来不讨喜 2021-01-13 16:05

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

5条回答
  •  旧巷少年郎
    2021-01-13 16:38

    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
    

提交回复
热议问题