如果满足条件,如何将值添加到前一行(How to add value to previous row if condition is met)
我想要做的是如果列b中的一行等于2,那么我想将3加到列a中前一行的值上。 如果条件不满足,那么我不希望前一行值改变。 当我尝试这段代码时,R会加入到后续行中。 并且我替换-1行引用并不重要,它总是添加到后续行。
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
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
原文:https://stackoverflow.com/questions/41419463
更新时间:2022-03-26 06:03