有没有办法在向量中找到R中具有实际值即非N / A的最后一个元素的索引

问题描述

这是我的载体

@H_404_3@x <- c("1","1","PNP004","10",NA,NA)

我需要找到一种方法来返回不是@H_404_3@NA的最终元素的索引/值。 有人知道这样做的好方法吗?

感谢您的帮助!

解决方法

Ind <- max(which(!is.na(yourvec)))
yourvec[Ind]
,

使用dplyr

dplyr::last(which(!is.na(yourvec)))
,

您可以从tail的结果中使用which来寻找向量的!is.na

tail(which(!is.na(x)),1)
#[1] 5

或for循环。

idxLNNA <- function(x) {
  if(length(x) > 0) {
    for(i in length(x):1) if(!is.na(x[i])) break
    if(i == 1 & is.na(x[i])) {0} else {i}
  } else {0}
}
idxLNNA(x)
#[1] 5

或者将cumsumwhich.max一起使用,如果只有NA,则返回1。

which.max(cumsum(!is.na(x)))
#[1] 5

或者从rev的{​​{1}}中减去length匹配。

x

基准:

length(x) - which.min(rev(is.na(x))) + 1 #Will fail in case on only NA
#length(x) - match(FALSE,is.na(rev(x))) + 1 #Alternative
#[1] 5