我想创建一个新列,在其中添加一个行值。例如,我想创建一个新列“ lane_deviation_additive”,在其中添加lane_deviationROW1 + lane_deviationROW2,然后再将lane_deviationROW3添加到该结果,然后将lane_deviationROW4添加到该结果,等等。
以下是可重现的示例:
example <- structure(list(ppid_trialn = c("1_1_4", "1_1_4", "1_1_4", "1_1_4",
"1_1_4", "1_1_4", "1_1_4", "1_1_4", "1_1_4", "1_1_4"), lane_deviation = c(0,
0.000155266125100885, 0.000155489294201173, 0.000155766010066695,
0.000155765951852893, 0.000155069487777508, 0.000154819918395414,
0.000156239855052866, 0.000155319064160215, 0.00015709614437562
)), class = c("grouped_df", "tbl_df", "tbl", "data.frame"), row.names = c(NA,
-10L), groups = structure(list(ppid_trialn = "1_1_4", .rows = list(
1:10)), row.names = c(NA, -1L), class = c("tbl_df", "tbl",
"data.frame"), .drop = TRUE))
我觉得使用dplyr和lag函数可以做到这一点,但是我不确定如何将下一行添加到添加前几行的结果中。任何帮助表示赞赏!
答案 0 :(得分:0)
example[,"lane_deviation_additive"] <-cumsum(example$lane_deviation)
答案 1 :(得分:0)
带有dplyr
library(dplyr)
example %>%
mutate(lane_deviation_additive = cumsum(lane_deviation))