删除前导和尾随 NA [英] Remove leading and trailing NA

查看:59
本文介绍了删除前导和尾随 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

这篇关于删除前导和尾随 NA的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆