我有一个数据集,其格式类似于:
amount | event
------ | ------
3 | FALSE
4 | FALSE
6 | TRUE
7 | FALSE
3 | FALSE
4 | TRUE
8 | FALSE
并且要基于event
列的值进行拆分和变异,并且仅当的值为event
TRUE时,才创建在行之前和之后填充值的新列。例如:
amount | event | before | after
------ | ----- | ----- | -----
3 | FALSE | NA | NA
4 | FALSE | NA | NA
6 | TRUE | 4 | 7
7 | FALSE | NA | NA
3 | FALSE | NA | NA
4 | TRUE | 3 | 8
8 | FALSE | NA | NA
我正在考虑ddply
with mutate
,但不确定如何在拆分后根据偏移量访问值。有任何想法吗?
您可以使用以下代码:
library(dplyr)
d %>%
mutate(before=ifelse(event,lag(amount),NA),
after =ifelse(event,lead(amount),NA))
# amount event before after
#1 3 FALSE NA NA
#2 4 FALSE NA NA
#3 6 TRUE 4 7
#4 7 FALSE NA NA
#5 3 FALSE NA NA
#6 4 TRUE 3 8
#7 8 FALSE NA NA
d
您的样本数据集在哪里:
d <- structure(list(amount = c(3, 4, 6, 7, 3, 4, 8), event = c(FALSE, FALSE, TRUE, FALSE, FALSE, TRUE, FALSE)), .Names = c("amount", "event"), row.names = c(NA, -7L), class = "data.frame")
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句