Zorro
Zorro

Reputation: 101

Variable Moving Mean Function

I need your help with a function in R. I have no idea to programm this: The input should be a data frame with all data, the column name in the data frame in which the data examined are specified and a numerical value indicating the variability of the mean value. The numerical value is to determine via how many values ​​the mean value should be formed. See for example: MyData:

A  B  C  D
A1 B1 2  D1
A2 B2 3  D2
A3 B3 -1 D3
A4 B4 0  D4
A5 B5 1  D5

The important column here is C, The numerical value here can be 2 to 5

The Output should be a dataframe with just the means

For Example:
Input: MyData, C, 2 Output:

C
(2+3)/2
(3-1)/2
(-1+0)/2
(0+1)/2

or for Example:
Input: MyData, C, 4 Output:

C
(2+3-1+0)/4
(3-1+0+1)/4

Of course, only the results of the bill should be seen, for the sake of understanding, I have written down the path I hope someone can help me. Thank you!

Upvotes: 0

Views: 40

Answers (2)

Lee
Lee

Reputation: 445

Take a look at the RcppRoll package.

library(RcppRoll)
roll_mean(df$C, 2)
roll_mean(df$C, 4)

Upvotes: 1

bringtheheat
bringtheheat

Reputation: 90

if youre open to using data.table:

df = as.data.frame(runif(10))
names(df) = 'c'
setDT(df)

df[ , output := (c + shift(c))/2]

Upvotes: 1

Related Questions