在忽略 NA 值的同时计算 cumsum() [英] Calculate cumsum() while ignoring NA values

查看:58
本文介绍了在忽略 NA 值的同时计算 cumsum()的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

考虑以下命名向量 x.

( x <- setNames(c(1, 2, 0, NA, 4, NA, NA, 6), letters[1:8]) )
# a  b  c  d  e  f  g  h 
# 1  2  0 NA  4 NA NA  6 

我想计算 x 的累积和,同时忽略 NA 值.许多 R 函数都有一个参数 na.rm,它在计算之前删除 NA 元素.cumsum() 不是其中之一,这使得这个操作有点棘手.

I'd like to calculate the cumulative sum of x while ignoring the NA values. Many R functions have an argument na.rm which removes NA elements prior to calculations. cumsum() is not one of them, which makes this operation a bit tricky.

我可以这样做.

y <- setNames(numeric(length(x)), names(x))
z <- cumsum(na.omit(x))
y[names(y) %in% names(z)] <- z
y[!names(y) %in% names(z)] <- x[is.na(x)]
y
# a  b  c  d  e  f  g  h 
# 1  3  3 NA  7 NA NA 13 

但这似乎过分了,并且会产生很多新的作业/副本.我相信有更好的方法.

But this seems excessive, and makes a lot of new assignments/copies. I'm sure there's a better way.

有什么更好的方法可以返回累积和同时有效地忽略 NA 值?

推荐答案

你想要这样的东西:

x2 <- x
x2[!is.na(x)] <- cumsum(x2[!is.na(x)])

x2

[edit] 或者,根据上面的评论建议,您可以将 NA 更改为 0 -

[edit] Alternatively, as suggested by a comment above, you can change NA's to 0's -

miss <- is.na(x)
x[miss] <- 0
cs <- cumsum(x)
cs[miss] <- NA
# cs is the requested cumsum

这篇关于在忽略 NA 值的同时计算 cumsum()的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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