如何填写“成功"R 中有 0 时的数字? [英] How to fill in the "succeeding" numbers whenever there is a 0 in R?

查看:62
本文介绍了如何填写“成功"R 中有 0 时的数字?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一串数字:

n1 = c(1, 1, 0, 6, 0, 0, 10, 10, 11, 12, 0, 0, 19, 23, 0, 0)

我需要用它后面"的相应数字替换 0 才能获得,同时将 0 单独留在尾部(因为它们后面没有任何东西):

I need to replace 0 with the corresponding number right "behind" it to get, while leaving the 0s in the tail alone (cause there is nothing right behind them):

n2 = c(1, 1, 6, 6, 10, 10, 10, 10, 11, 12, 19, 19, 19, 23, 0, 0)

如何从 n1 到 n2?

How can I get from n1 to n2?

这似乎是一个比我之前问过的问题更难的问题:

This seems to be a much harder question than the one I've asked earlier:

如何每当 R 中有 0 时填写前面的数字?

flodel 提出了一个优雅的解决方案:

where flodel has come up with an elegant solution:

n2 <- n1[cummax(seq_along(n1) * (n1 != 0))]

然而,这个解决方案在这里不起作用;我已经尝试过但未能调整代码.

However, this solution does not work here; I've tried but failed to adapt the code.

其他人能想出一个优雅的解决方案吗?

Can someone else figure out an elegant solution?

提前致谢!

推荐答案

如果向量中没有 NA,你可以使用 na.locf 从包 zoo:

If you don't also have NA in the vector, you can use na.locf from package zoo:

n1[n1==0] <- NA
n2 = na.locf(n1, na.rm=FALSE, fromLast=TRUE)
n2[is.na(n2)] <- 0
n2
## [1]  1  1  6  6 10 10 10 10 11 12 19 19 19 23  0  0

这篇关于如何填写“成功"R 中有 0 时的数字?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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