创建一种新的基于列的另一列的多行
问题描述:
我有一个数据帧,因为这创建一种新的基于列的另一列的多行
> df<-data.frame(index=c(1,2,3,4,5,6),value=c(2,3,5,8,11,12))
> df
index value
1 1 2
2 2 3
3 3 5
4 4 8
5 5 11
6 6 12
我想创建它等于列值通过索引的三个相邻值之和的新列柱索引,即
> df_res
index value res
1 1 2 NA
2 2 3 10
3 3 5 16
4 4 8 24
5 5 11 31
6 6 12 NA
的RES第二行是(2,3,5),第三和(3,5,8)等的总和(第一个和最后行res不要紧,我暂时将它设置为NA)
我怎样才能在R中完成它?
答
如果使用data.table
:
library(data.table)
setDT(df)
df[,res:=value+shift(value,1)+shift(value,1,type="lead")]
答
df$res <- sapply(df$index, function(index)
ifelse(index > 1 & index < nrow(df),sum(df$value[(index - 1):(index + 1)]), NA))
index value res
1 1 2 NA
2 2 3 10
3 3 5 16
4 4 8 24
5 5 11 31
6 6 12 NA
答
使用的头和尾:
df$res <- df$value + c(tail(df$value, -1), NA) + c(NA, head(df$value, -1))
df
# index value res
# 1 1 2 NA
# 2 2 3 10
# 3 3 5 16
# 4 4 8 24
# 5 5 11 31
# 6 6 12 NA
或者用动物园:
df$res <- zoo::rollsum(df$value, 3, na.pad = TRUE)
答
可以使用dplyr
和roll_sum
吨o不要:
df %>%
mutate(v2 = roll_sum(value, 3,fill = NA))
其给出:
index value v2
1 1 2 NA
2 2 3 10
3 3 5 16
4 4 8 24
5 5 11 31
6 6 12 NA
的可能的复制[R dplyr轧制Σ(http://*.com/questions/30153835/r-dplyr-rolling-sum) – Aramis7d