Amit
Amit

Reputation: 793

how to extract 1st and last non empty value from vector in R?

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

Answers (2)

AnilGoyal
AnilGoyal

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

Ronak Shah
Ronak Shah

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

Related Questions