Home > Blockchain >  How to split a vector into list breaking at a specific value
How to split a vector into list breaking at a specific value

Time:02-16

How can I split the following vector to list with every new element whereever an empty '' value is encountered?

For e.g. Given the following input-

x <- c("abc", "", "a", "b", "c", "", "ab", "ac", "", "a", "a", "a", 
"a", "", "b")

x
 [1] "abc" ""    "a"   "b"   "c"   ""    "ab"  "ac"  ""    "a"   "a"   "a"   "a"   ""    "b"  

I want the following list as output

list("abc", c("a", "b", "c"), c("ab", "ac"), c("a", "a", "a", 
"a"), "b")

[[1]]
[1] "abc"

[[2]]
[1] "a" "b" "c"

[[3]]
[1] "ab" "ac"

[[4]]
[1] "a" "a" "a" "a"

[[5]]
[1] "b"

CodePudding user response:

Create a logical vector based on the blank elements (i1), get the cumulative sum on the logical vector to create group for splitting the subset of vector (i.e. without the blanks)

i1 <- !nzchar(x)
unname(split(x[!i1], cumsum(i1)[!i1]))

-output

[[1]]
[1] "abc"

[[2]]
[1] "a" "b" "c"

[[3]]
[1] "ab" "ac"

[[4]]
[1] "a" "a" "a" "a"

[[5]]
[1] "b"
  • Related