简体   繁体   English

如何创建一个列,指示观察结果与R中另一个观测值的滞后?

[英]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.

相关问题 从不同列中的另一个观察值中减去一个观察值,并将特定值添加到结果中以在 R 的第一列中创建一个新观察值 - Subtract an observation from another in different column and add a specific value to the result to create a new observation in the first column in R 如何在 R 的观察中计算单词 - How can I count words in an observation in R 使用 R 观察滞后/超前组 - Lag/lead groups of observation with R 在R的另一列的行尾追加观察 - Append observation at end of row from another column in R 根据另一列的先前观察值创建新变量 - Create new variable based on prior observation value from another column rpart 创建一个表,指示一个观察是否属于一个节点 - rpart create a table that indicates if an observation belongs to a node or not R 中的行到列观察 - Observation in Row to Column in R 如何在R中的直方图中突出显示观察区域 - How do I highlight an observation's bin in a histogram in R 如何使用另一列的数据 (Y) 创建和填充新列 (Z),但前提是存在第三列 (X) 中的某个观察? - How to create and populate a new column (Z) with another column's data (Y) but only if a certain observation in a third column (X) is present? 如何根据字符串列为每个观察创建一个包含多行的新数据框? - How can I create a new data frame with several rows for each observation based on string column?
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM