R用下一个非零值替换数据帧中的零

编程入门 行业动态 更新时间:2024-10-12 03:21:12
本文介绍了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

感谢您的帮助.

推荐答案

这是 zoo 的 na.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用下一个非零值替换数据帧中的零

本文发布于:2023-10-27 04:30:20,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1532321.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:数据   非零值

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!