split strings on first and last commas

后端 未结 5 1932
生来不讨喜
生来不讨喜 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:39

    You can do a simple strsplit here on that column

    popshift<-sapply(strsplit(my.data$my.string,","), function(x) 
        c(x[1], paste(x[2:(length(x)-1)],collapse=","), x[length(x)]))
    
    desired.result <- cbind(data.frame(my.string=t(popshift)), my.data[-1])
    

    I just split up all the values and make a new vector with the first, last and middle strings. Then i cbind that with the rest of the data. The result is

      my.string.1 my.string.2 my.string.3 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
    

提交回复
热议问题