String transformation in R | Grouping words of a string

后端 未结 5 1230
孤街浪徒
孤街浪徒 2021-01-20 10:02

I want to group the words of string(given below)

text=\"Lorem,ipsum,dolor,sit,amet,consectetuer\"

like this

textNew=\"Lore         


        
5条回答
  •  心在旅途
    2021-01-20 10:38

    You could also do:

      library(stringr)
       txt2 <- str_extract_all(text, "[^,]+")[[1]]
       paste(paste(txt2[-length(txt2)],txt2[-1],sep=" "), collapse=", ")
       #[1] "Lorem ipsum, ipsum dolor, dolor sit, sit amet, amet consectetuer"
    

    Or

      library(gsubfn)
       paste(strapply(text, "([^,]+),(?=([^,]+))", paste, backref= -2, perl=TRUE)[[1]], collapse=",")
       #[1] "Lorem ipsum,ipsum dolor,dolor sit,sit amet,amet consectetuer"
    

提交回复
热议问题