删除前导和尾随 NA

问题描述:

我需要从向量中删除前导尾随缺失值(NA).数字之间的 NA 应该保留.请注意,我的下一步是索引另一个没有 NA 的向量,并仅保留与第一个向量中位置相同的值.例子如下:

I need to delete leading and trailing missing values (NA) from a vector. NAs between numbers should be kept. Note that my next step is index another vector without NA and keep only values with the same position as in first vector. Here is the example:

a <- c(NA, NA, NA, NA, NA, 5,2,3,1,2,1,5,2, NA, NA, 2,3,2,NA,NA,NA)
b <- sample(1:21)

我想要的输出是:

a1 <- c(5,2,3,1,2,1,5,2,NA,NA,2,3,2)
# leading and trailing NAs removed

b1 <- b[6:18]
# subset with the indices kept in "a" above.

我想我可以通过条件循环来做到这一点,但我想对其进行矢量化.感谢帮助!

I thing I can do this with come conditional loop but I want to vectorize it. Thx for help!

查找第一个和最后一个非 NA 值并保留向量的那部分:

Look for the first and the last non-NA value and keep that part of the vector:

a1 <- a[min(which(!is.na(a))):max(which(!is.na(a)))]

> a1
[1]  5  2  3  1  2  1  5  2 NA NA  2  3  2