Reputation: 793
i have a vector
c(NA,13,NA, 12, 15, NA)
I need to extract 1st non nan value i.e 13 and last non nan value i.e 15
Upvotes: 0
Views: 256
Reputation: 26218
#first
v[min(which(!is.na(v)))]
[1] 13
#last
v[max(which(!is.na(v)))]
[1] 15
#where v is
v <- c(NA,13,NA, 12, 15, NA)
Upvotes: 2
Reputation: 388797
You can use na.omit
to drop NA
values and subset the first and last value.
x <- c(NA,13,NA, 12, 15, NA)
first_non_NA_value <- na.omit(x)[1]
last_non_NA_value <- rev(na.omit(x))[1]
first_non_NA_value
#[1] 13
last_non_NA_value
#[1] 15
Upvotes: 1