简体   繁体   中英

Returning values after last NA in a vector

Returning values after last NA in a vector

I can remove all NA values from a vector

v1 <- c(1,2,3,NA,5,6,NA,7,8,9,10,11,12)
v2 <- na.omit(v1)
v2

but how do I return a vector with values only after the last NA

c( 7,8,9,10,11,12)

Thank you for your help.

You could detect the last NA with which and add 1 to get the index past the last NA and index until the length(v1) :

 v1[(max(which(is.na(v1)))+1):length(v1)]
[1]  7  8  9 10 11 12

You could detect the last NA with which

v1[(tail(which(is.na(v1)), 1) + 1):length(v1)]
# [1]  7  8  9 10 11 12

However, the most general - as @MrFlick pointed out - seems to be this:

tail(v1, -tail(which(is.na(v1)), 1))
# [1]  7  8  9 10 11 12

which also handles the following case correctly:

v1[13] <- NA
tail(v1, -tail(which(is.na(v1)), 1))
# numeric(0)

To get the null NA case, too,

v1 <- 1:13

we can do

if (any(is.na(v1))) tail(v1, -tail(which(is.na(v1)), 1)) else v1
# [1]  1  2  3  4  5  6  7  8  9 10 11 12 13

Data

v1 <- c(1, 2, 3, NA, 5, 6, NA, 7, 8, 9, 10, 11, 12)
v1 <- c(1,2,3,NA,5,6,NA,7,8,9,10,11,12)
v1[seq_along(v1) > max(0, tail(which(is.na(v1)), 1))]
#[1]  7  8  9 10 11 12

v1 = 1:5
v1[seq_along(v1) > max(0, tail(which(is.na(v1)), 1))]
#[1] 1 2 3 4 5

v1 = c(1:5, NA)
v1[seq_along(v1) > max(0, tail(which(is.na(v1)), 1))]
#integer(0)

The following will do what you want.

i <- which(is.na(v1))
if(i[length(i)] < length(v1)){
  v1[(i[length(i)] + 1):length(v1)]
}else{
  NULL
}
#[1]  7  8  9 10 11 12

Here's an alternative solution that does not use indices and only vectorised operations:

after_last_na = as.logical(rev(cumprod(rev(! is.na(v1)))))
v1[after_last_na]

The idea is to use cumprod to fill the non- NA fields from the last to the end. It's not a terribly useful solution in its own right (I urge you to use the more obvious, index range based solution from other answers) but it shows some interesting techniques.

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