2015-08-15 34 views
1

我在使用lag功能(dplyr) 設置default = 0的R - dplyr滯後默認爲0的錯誤

dta %>% 
group_by(id) %>% 
mutate(mLag = value.x == lag(value.y, default = 0)) 

我得到的TRUE/FALSE代替0-1時遇到的問題。

然而,當我使用lag這樣,我得到我想輸出有:

lag(dta$value.x == dta$value.y, default = 0) 
0 1 1 1 0 1 1 0 1 1 1 1 0 1 1 

不知道如何解決這個問題?

感謝

數據

dta = structure(list(id = c(1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 
1L, 1L, 1L, 1L, 1L), variable = structure(1:15, .Label = c("08:00", 
"08:15", "08:30", "08:45", "09:00", "09:15", "09:30", "09:45", 
"10:00", "10:15", "10:30", "10:45", "11:00", "11:15", "11:30", 
"11:45", "12:00", "12:15", "12:30", "12:45", "13:00", "13:15", 
"13:30", "13:45", "14:00", "14:15", "14:30", "14:45", "15:00", 
"15:15", "15:30", "15:45", "16:00", "16:15", "16:30", "16:45", 
"17:00", "17:15", "17:30", "17:45", "18:00", "18:15", "18:30", 
"18:45", "19:00", "19:15", "19:30", "19:45", "20:00", "20:15", 
"20:30", "20:45", "21:00", "21:15", "21:30", "21:45"), class = "factor"), 
sex.x = c("m", "m", "m", "m", "m", "m", "m", "m", "m", "m", 
"m", "m", "m", "m", "m"), value.x = c("partner", "partner", 
"partner", "partner", "alone", "alone", "nuclear", "nuclear", 
"nuclear", "nuclear", "nuclear", "children", "children", 
"children", "children"), sex.y = c("f", "f", "f", "f", "f", 
"f", "f", "f", "f", "f", "f", "f", "f", "f", "f"), value.y = c("partner", 
"partner", "partner", "alone", "alone", "alone", "children", 
"nuclear", "nuclear", "nuclear", "nuclear", "nuclear", "children", 
"children", "children")), .Names = c("id", "variable", "sex.x", 
"value.x", "sex.y", "value.y"), row.names = c(NA, 15L), class = "data.frame") 
+0

'as.numeric'應該工作 – jenesaisquoi

+0

@RichardScriven - 遺憾的是它不工作,我仍然得到'NA' – giacomo

回答

1

我想你可能弄丟了LHS value.x ==。它應該進入lag()函數。

這似乎是這樣做的。

group_by(dta, id) %>% 
    mutate(mLag = lag(value.x == value.y, default = 0)) 
# Source: local data frame [15 x 7] 
# Groups: id 
# 
# id variable sex.x value.x sex.y value.y mLag 
# 1 1 08:00  m partner  f partner 0 
# 2 1 08:15  m partner  f partner 1 
# 3 1 08:30  m partner  f partner 1 
# 4 1 08:45  m partner  f alone 1 
# 5 1 09:00  m alone  f alone 0 
# 6 1 09:15  m alone  f alone 1 
# 7 1 09:30  m nuclear  f children 1 
# 8 1 09:45  m nuclear  f nuclear 0 
# 9 1 10:00  m nuclear  f nuclear 1 
# 10 1 10:15  m nuclear  f nuclear 1 
# 11 1 10:30  m nuclear  f nuclear 1 
# 12 1 10:45  m children  f nuclear 1 
# 13 1 11:00  m children  f children 0 
# 14 1 11:15  m children  f children 1 
# 15 1 11:30  m children  f children 1 
+0

非常感謝你 – giacomo