我正在尝试创建一个新变量,它是先前行和列的函数。我在 dplyr 中找到了 lag() 函数,但它不能完全完成我想要的。
library(dplyr)
x = data.frame(replicate(2, sample(1:3,10,rep=TRUE)))
X1 X2
1 1 3
2 2 3
3 2 2
4 1 3
5 2 3
6 2 1
7 3 2
8 1 1
9 1 3
10 2 2
x = mutate(x, new_col = # if x2==1, then the value of x1 in the previous row,
# if x2!=1, then 0))
我最好的尝试:
foo = function(x){
if (x==1){
return(lag(X1))
}else{
return(0)
}
x = mutate(x, new_col=foo(X1))
最佳答案
我们可以使用 ifelse
x %>%
mutate(newcol = ifelse(X2==1, lag(X1), 0))
关于r - 如何使用前一行和前一列的值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45308743/