Zwentibold
Zwentibold

Reputation: 139

Manipulating lists in R

I have a list that looks like this:

mylist <- list("a", "b", "c", NA, "d", "e", "f", NA, "g", "h", "i", NA, "j", "k", "l", NA,
               "m", "n", "o", NA, "p", "q", "r", NA, "s", "t", "u", NA, "v", "w", "x", NA,
               "y", "z")
str(mylist)
# List of 34
# $ : chr "a"
# $ : chr "b"
# $ : chr "c"
# $ : logi NA
# $ : chr "d"
# $ : chr "e"
# $ : chr "f"
# $ : logi NA
# $ : chr "g"
[list output truncated]

I want it to look like this:

str(mylist)
$ : chr [1:3] "a" "b" "c"
$ : chr [1:3] "d" "e" "f"
$ : chr [1:3] "g" "h" "i"
[list output truncated]

In other words, I want a list in which all of the elements up to each NA is made into its own list. I suspect this is not difficult to do, but I can't figure it out! Thanks for your help.

Upvotes: 2

Views: 122

Answers (1)

jeremycg
jeremycg

Reputation: 24945

You could try:

lapply(split(unlist(x), cumsum(is.na(x))), function(z) z[!is.na(z)])

Upvotes: 5

Related Questions