如果满足条件,如何将值添加到前一行 [英] How to add value to previous row if condition is met

查看:58
本文介绍了如果满足条件,如何将值添加到前一行的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想要做的是,如果 b 列中的一行等于 2,那么我想将 a 列中前一行的值加 3.如果不满足条件,那么我不希望前一行值发生变化.当我尝试此代码时,R 正在添加到后续行.我用什么替换 -1 行引用并不重要,它总是添加到后续行中.

What I am trying to do is if a row in column b is equal to 2 then I want to add 3 to the value of the previous row in column a. And if the condition is not met, then I don't want the previous row value to change. When I try this code however R is adding to the subsequent row. And it doesn't matter what I replace the -1 row reference with it always adds to the subsequent row.

df$a[-1] <- ifelse(df$b == 2, df$a[-1] + 3, df$a[-1])

Have                               Want
a b                                a b
0 1                                0 1
1 3                                4 3
2 2                                2 2
2 4                                2 4
4 5                                4 5

推荐答案

另一种方法

df <- data.frame(a=c(0, 1, 2, 2, 3),
             b=c(1, 3, 2, 4, 4))

df$a[c(df$b[-1], 0) == 2] <- df$a[c(df$b[-1], 0) == 2] + 3

这篇关于如果满足条件,如何将值添加到前一行的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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