Reputation: 723
I have a dataframe as this
> 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
I want to create a new column which equals to the the sum of three adjacent values of column value indexed by column index, that is
> 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
The second row of res is the sum of (2,3,5), third sum(3,5,8) etc. (the first and last row of res do not matter, and I temporarily set it as NA)
How can I get it done in R?
Upvotes: 3
Views: 1756
Reputation: 1297
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
Upvotes: 0
Reputation: 56229
Using head and tail:
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
Or using zoo:
df$res <- zoo::rollsum(df$value, 3, na.pad = TRUE)
Upvotes: 0
Reputation: 2496
you can use dplyr
and roll_sum
to do:
df %>%
mutate(v2 = roll_sum(value, 3,fill = NA))
which gives:
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
Upvotes: 1
Reputation: 2060
If you use data.table
:
library(data.table)
setDT(df)
df[,res:=value+shift(value,1)+shift(value,1,type="lead")]
Upvotes: 1