简体   繁体   中英

R: Split character vector of length n>1, at specific character, into a list of n vectors

I have a vector with repeating characters, and I need to break it at the positions where character is "" (empty character), thus getting a list of as many character vectors as my separator points. Vector t describes the situation now, while S is the result as it should be. I understand that using "" as separator could be a problem. In that case I could substitute it with a special character.

set.seed<-123
S<-list(character(10))
t<-as.vector(NULL)
for (i in 1:10) {
  temp<-c("",rep("a",rbinom(1,10,0.5)), rep("b", rbinom(1,10,0.5)), rep("c", rbinom(1,10,0.5)))
  t<-append(t,temp)
  S[[i]]<-temp[temp!=""]
}

Thank you.

There are probably better ways but this seems to get close to what you want

trythis <- split(t, cumsum(t == ""))

Added

You edited the question to remove the blanks from S . You could adapt my answer to

blanks  <- which(t == "")
trythis <- split(t[-blanks], cumsum(t == "")[-blanks])

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM