Reputation: 796
x=c(NA, 2, -3, NA, -5, 5, -7, -8, -9, -10, NA, -2, 2, -14, -15, NA, -17, 2, NA, -20)
I would like to select the first 10 values that are not NA
.
so I do:
head(x[!is.na(x)], 10)
Now I want to know how many NA were ignored:
sum(is.na(head(x[is.na(x)], 10)))
# [1] 5
which is not correct: it should be 3
Upvotes: 0
Views: 93
Reputation: 887088
We need logicla vector on the subset of actual vector and not on the NA only data
sum(is.na(head(x, 10)))
#[1] 3
head(x[is.na(x)], 10)
#[1] NA NA NA NA NA
gives only NAs as we are subsetting the NA elements
Based on the logic in comments, one way is
i1 <- !is.na(x)
i1[i1] <- seq_along(i1[i1])
sum(is.na(head(x, which(i1 == 10))))
Upvotes: 3
Reputation: 748
This should do it:
sum(is.na(head(x, which(cumsum(!is.na(x)) == 10))))
The cumsum
of the logical vector given by !is.na
gives us the index of the tenth non-NA
number, which is the input we want for the head
function (because we want all values of until we get to the tenth non-NA
value).
Upvotes: 2