I have the following vector called input:
input <- c(1,2,1,NA,3,2,NA,1,5,6,NA,2,2)
[1] 1 2 1 NA 3 2 NA 1 5 6 NA 2 2
I would like to split this vector into multiple vectors by each NA. So the desired output should look like this:
> output
[[1]]
[1] 1 2 1
[[2]]
[1] 3 2
[[3]]
[1] 1 5 6
[[4]]
[1] 2 2
As you can see every time a NA appears, it splits into a new vector. So I was wondering if anyone knows how to split a vector by each NA into multiple vectors?
Using a similar logic to @tpetzoldt, but removing the NAs before the split:
split(na.omit(input), cumsum(is.na(input))[!is.na(input)])
$`0`
[1] 1 2 1
$`1`
[1] 3 2
$`2`
[1] 1 5 6
$`3`
[1] 2 2
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With