[英]How can I create a column that indicates the observation's lag from another observation in R?
I have dataframe d with a Boolean variable event indicating whether a certain event occurred on a given date. 我有一个带有布尔变量事件的数据框d,指示某个事件是否在给定日期发生。 I want to create a new variable that indicates how many observations (days) away the closest event is. 我想创建一个新变量,指示距离最近的事件有多少观察(天)。
d=structure(list(date = structure(c(-365, -364, -363, -362, -361,
-360, -359, -358, -357, -356, -355, -354, -353, -352, -351, -350,
-349, -348, -347, -346), class = "Date"), event = c(TRUE,
FALSE, FALSE, FALSE, FALSE, FALSE, FALSE, FALSE, FALSE, FALSE,
FALSE, FALSE, FALSE, FALSE, TRUE, FALSE, FALSE, FALSE, FALSE,
FALSE)), .Names = c("date", "event"), row.names = c(NA, 20L
), class = "data.frame")
Is there a function that will do this? 有没有这样做的功能?
Something like 就像是
apply(abs( sapply( which(d$event), "-", 1:nrow(d) )),1,min)
will generalize @DWin's answer for more than 2 TRUE
values. 将推广@DWin的答案超过2个TRUE
值。
> pmin( abs( sapply( which(d$event), "-", 1:nrow(d) )[,1] ) ,
abs( sapply( which(d$event), "-", 1:nrow(d) )[,2] ) )
[1] 0 1 2 3 4 5 6 7 6 5 4 3 2 1 0 1 2 3 4 5
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.