2017-07-25 93 views
3

我想創建一個新的變量,它是以前的行和列的函數。我在dplyr中找到了lag()函數,但它無法完成我想要的。R和dplyr:如何使用前一行和列的值

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)) 

回答

3

我們可以使用ifelse

x %>% 
    mutate(newcol = ifelse(X2==1, lag(X1), 0)) 
2

在基礎R,您可以使用

x$newcol <- (x$X2 == 1) * c(NA, tail(x$X1, -1)) 

(x$X2 == 1)確保0爲所有元素X2不等於l到1,當X2 == 1時,兩項的倍數將返回X1的滯後值。

相關問題