Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Split vector by each NA in R

Tags:

split

r

vector

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?

like image 283
Quinten Avatar asked Jan 22 '26 17:01

Quinten


1 Answers

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
like image 52
tmfmnk Avatar answered Jan 25 '26 08:01

tmfmnk