Reputation: 1587
My dataset has the following form:
df<- data.frame(c("a", "a", "a", "a", "a", "a", "a", "a", "b", "b", "b", "b", "b", "b", "b", "b"),
c(1, 1, 1, 1, 2, 2, 2, 2, 1, 1, 1, 1, 2, 2, 2, 2),
c(1, 2, 3, 4, 1, 2, 3, 4, 1, 2, 3 , 4, 1, 2, 3, 4),
c(25, 75, 20, 40, 60, 50, 20, 10, 20, 30, 40, 60, 25, 75, 20, 40))
colnames(df)<-c("car", "year", "mnth", "val")
For clarity I show it here as well:
car year mnth val
1 a 1 1 25
2 a 1 2 75
3 a 1 3 20
4 a 1 4 40
5 a 2 1 60
6 a 2 2 50
7 a 2 3 20
8 a 2 4 10
9 b 1 1 20
10 b 1 2 30
11 b 1 3 40
12 b 1 4 60
13 b 2 1 25
14 b 2 2 75
15 b 2 3 20
16 b 2 4 40
I would like to add a new column tmp
to df
where, for a particular row, the value of tmp
should be the average of df$val
and the 3 preceeding values. Some examples of tmp
are shown here
#row 3: mean(25,75,20)=40
#row 4: mean(25,75,20,40)=40
#row 5: mean(75,20,40,60)=48.75
#row 16: mean(25,75,20,40)=40
Is there an efficient way to do this in R without using for
-loops?
Upvotes: 1
Views: 88
Reputation: 32548
For each value, calculate the mean of a rolling window which includes the value as well as preceding 3 values (from index i-3
up to index i
in the solution below). For cases when i-3
is negative, you can just use 0
(max((i-3),0)
)
sapply(seq_along(df$val), function(i)
mean(df$val[max((i-3),0):i], na.rm = TRUE))
#[1] 25.00 50.00 40.00 40.00 48.75 42.50 42.50 35.00 25.00
#[10] 20.00 25.00 37.50 38.75 50.00 45.00 40.00
Also consider rollmean
of zoo
library(zoo)
c(rep(NA,3), rollmean(x = df$val, k = 4))
#[1] NA NA NA 40.00 48.75 42.50 42.50 35.00 25.00 20.00 25.00
#[12] 37.50 38.75 50.00 45.00 40.00
#FURTHER TWEAKING MAY BE NECESSARY
Upvotes: 1
Reputation: 1421
Or simply so
library(dplyr)
df$tmp <- (df$val+lag(df$val,1)+lag(df$val,2)+lag(df$val,3))/4
This does not use any loop. It simply shift the list and sum the shifted lists.
For example if you define
a <- c(1,2,3,4,5)
then
lag(a)
is
NA 1 2 3 4
I hope it can help you.
Upvotes: 2
Reputation: 92292
Here's (somewhat) vectorized solution using data.table::shift
library(data.table)
colMeans(do.call(rbind, shift(df$val, 0:3)), na.rm = TRUE)
## [1] 25.00 50.00 40.00 40.00 48.75 42.50 42.50 35.00 25.00 20.00 25.00 37.50 38.75 50.00 45.00 40.00
Or as @Frank suggested
rowMeans(setDF(shift(df$val, 0:3)), na.rm = TRUE)
Upvotes: 4
Reputation: 2469
You could also use data.table
library(data.table)
setDT(df)
df[, tmp := (val + shift(val,1,type="lag") + shift(val,2,type="lag") + shift(val,3,type="lag"))/4]
Upvotes: 1