关于如何使用列 A 的值创建新列 B 的任何想法,同时使用新创建的列 B 的上方行的值?
B的值应对应于:
A0 = value of the row above.
A1 = 1.
A2 = value of the row above + 1.
当前数据框 + 预期结果
Dataframe Desired outcome
A A B
1 1 1
0 0 1
2 2 2
0 0 2
2 2 3
0 0 3
2 2 4
0 0 4
2 2 5
0 0 5
2 2 6
0 0 6
1 1 1
0 0 1
1 1 1
0 0 1
2 2 2
0 0 2
2 2 3
0 0 3
1 1 1
0 0 1
2 2 2
0 0 2
Data Frame
A <- c(1,0,2,0,2,0,2,0,2,0,2,0,1,0,1,0,2,0,2,0,1,0,2,0)
Bdesiredoutcome <- c(1,1,2,2,3,3,4,4,5,5,6,6,1,1,1,1,2,2,3,3,1,1,2,2)
df = data.frame(A,Bdesiredoutcome)
我尝试使用dpylr, mutate(), case_when()
但lag()
一直遇到错误。由于使用该lag()
功能。使用lag(A)
时无法生成期望的结果。关于如何解决这个问题的任何想法?
df <- df %>%
mutate(B = case_when((A == 0) ~ lag(B),
(A == 1) ~ 1,
(A == 2) ~ (lag(B)+1)
))
Error in UseMethod("mutate_") :
no applicable method for 'mutate_' applied to an object of class "function"
In addition: Warning message: