0

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!

Zorro
  • 91
  • 1
  • 8

2 Answers2

1

if youre open to using data.table:

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

df[ , output := (c + shift(c))/2]
  • Thank you for your Answer, but I dont get it now. How can it work in a function like: movingMean <- function(data, feature, value?) – Zorro Dec 12 '17 at 14:35
  • ah yes, no, it's just a simple lag/lead feature of data.table. I would use the answer provided by @Lee, works like a charm. – bringtheheat Dec 12 '17 at 14:36
1

Take a look at the RcppRoll package.

library(RcppRoll)
roll_mean(df$C, 2)
roll_mean(df$C, 4)
Lee
  • 405
  • 2
  • 10