0

For a data frame that looks like:

Value  Id
 1      xxx-rrr-ttt
 78     ggg-oop-rty
 97     fad-dar-oki
 ..      ..
 ..      ..
 ..      ..

I need to calculate the rolling-mean at each row. So for a data frame s, rolling mean at each row will be represented as s.mean. Is there any inbuilt function in R that can calculate rolling-mean ? I tried the following:

rollapply(data)

but it throws an error argument "width" is missing, with no default. I could not understand this error and what is meant by the width

Jatt
  • 665
  • 2
  • 8
  • 20
  • You can use `rollmean` from `zoo`. With `rollapply`, you need to pass the function and width argument. You can check the documentation of `?rollapply` if there is doubt. `width - numeric vector or list. In the simplest case this is an integer specifying the window width (in numbers of observations) which is aligned to the original sample according to the align argument. Alternatively, width can be a list regarded as offsets compared to the current time, see below for details.` – akrun Mar 28 '18 at 02:24
  • @akrun I have already imported the package, but not sure how to use the function. – Jatt Mar 28 '18 at 02:25
  • @akrun Could you show with an example as an answer? – Jatt Mar 28 '18 at 02:26
  • you probably need to pass a column name instead of complete dataframe. What is your expected output? – Ronak Shah Mar 28 '18 at 02:30
  • @RonakShah No. It gives an error about width – Jatt Mar 28 '18 at 02:31
  • @Jatt Please check the example I provided as a a solution – akrun Mar 28 '18 at 02:31
  • @downvoter Any reason? – Jatt Mar 28 '18 at 02:33
  • 1
    @RonakShah How did you term it as duplicate? Any question related to `moving mean` cannot be a duplicate. – Jatt Mar 28 '18 at 02:50
  • @Jatt I see no difference between the question you have asked and the one marked. If you would have read the documentation at `?rollmean` or `?rollapply` you would have got the answer yourself. Moreover, if you still think your question is different from the one marked please feel free to vote to reopen the question. – Ronak Shah Mar 28 '18 at 02:55

1 Answers1

3

We can get the same output with rollmean or rollapply

library(zoo)
rollmean(df1$Value, k = 3)
#[1]  0.13677590  0.12419375  0.22781866  0.17661827  0.51935576  0.08137071 -0.29009330 -0.43751774
rollapply(df1$Value, width = 3, FUN = mean)
#[1]  0.13677590  0.12419375  0.22781866  0.17661827  0.51935576  0.08137071 -0.29009330 -0.43751774

data

set.seed(24)
df1 <- data.frame(Value = rnorm(10))
Community
  • 1
  • 1
akrun
  • 874,273
  • 37
  • 540
  • 662