R用下一个非零值替换数据帧中的零 [英] R replacing zeros in dataframe with next non zero value

查看:34
本文介绍了R用下一个非零值替换数据帧中的零的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个包含零值列的数据框:

I have a dataframe with a column containing zero values:

a <- 1:10
b <- c(1, 0, 0, 0, 0, -1, -1, 0, 0, 1)
df <- data.frame(a, b)
df

如何将零值替换为最后一个非零值,即 df$b 列:

How can I replace the zero values with the last non zero value ie column df$b to be:

 1,-1,-1,-1,-1,-1,-1,1,1,1

感谢您的帮助.

推荐答案

这是 zoona.locf 的一种方法.虽然这个方法在过程中确实把一些值改成了NA,但是代码很好,很轻松.

Here's one way with na.locf from zoo. Although this method does change some values to NA in the process, the code is nice and painless.

library(zoo)
na.locf(with(df, ifelse(b == 0, NA_real_, b)), fromLast = TRUE)
# [1]  1 -1 -1 -1 -1 -1 -1  1  1  1

另一种替代方法,在长向量上可能比 ifelse 更快,是

An alternative to this, and one that might be faster than ifelse on long vectors, is

na.locf(with(df, { is.na(b) <- b == 0; b }), fromLast = TRUE)
# [1]  1 -1 -1 -1 -1 -1 -1  1  1  1

这篇关于R用下一个非零值替换数据帧中的零的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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