r-dplyr滞后默认值0错误

r-dplyr滞后默认值0错误,r,dplyr,R,Dplyr,我在使用lag功能时遇到问题(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 你

我在使用
lag
功能时遇到问题(
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")

我想你可能把lhs
值放错地方了。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

as.numeric
应work@RichardScriven-不幸的是,它不起作用,我仍然得到
NA