R仅在第一个非零值之后转换NA [英] R Convert NA's only after the first non-zero value

查看:72
本文介绍了R仅在第一个非零值之后转换NA的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个大型数据集,其中包含一列ID,然后是每个ID的每月时间序列.此集合中经常缺少值,但是我想做的是将第一个非零值之后的所有NA都替换为零,而将第一个非零值之前的所有NA都保留为NA.

I have a large data set which consists of a columns of IDs followed by a monthly time series for each ID. There are frequent missing values in this set, but what I would like to do is replace all NAs after the first non-zero with a zero while leaving all the NAs before the first non-zero value as NA's.

例如

[NA NA NA 1 2 3 NA 4 5 NA]将更改为[NA NA NA 1 2 3 0 4 5 0]

[NA NA NA 1 2 3 NA 4 5 NA] would be changed to [NA NA NA 1 2 3 0 4 5 0]

非常感谢你们提供的帮助或建议!

Any help or advice you guys could offer would be much appreciated!

推荐答案

使用match()和数字索引容易做到:

Easy to do using match() and numeric indices:

  • 使用match()查找非NA值的第一个匹配项
  • 使用which()将逻辑向量从is.na()转换为数字索引
  • 使用该信息在x中找到正确的位置
  • use match() to find the first occurence of a non-NA value
  • use which() to convert the logical vector from is.na() to a numeric index
  • use that information to find the correct positions in x

因此:

x <- c(NA,NA,NA,1,2,3,NA,NA,4,5,NA)
isna <- is.na(x)
nonna <- match(FALSE,isna)
id <- which(isna)
x[id[id>nonna]] <- 0

给予:

> x
 [1] NA NA NA  1  2  3  0  0  4  5  0

这篇关于R仅在第一个非零值之后转换NA的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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