2

How do I provide multiple parameters and variables to an apply function? I'd like to pass vectir c(1, 2) to argument l and varaibles c(x, x1) to argument k.

Desired Output should have four columns instead of two

Example

library(zoo)
datt <- data.frame(x = rnorm(100),
           x2 = rnorm(100))
mapply(function(l, k) c(rollmean(datt[,k], l), rep(NA, l-1)),
       c(1, 2),
       c("x", "x2"))

Output

           x         x2
1 -0.2688922  0.9506357
2  0.1402062  0.7324266
3  0.1391136 -1.7412695
4  1.4542990  2.1617833
5 -0.9409344  2.0495386
6 -0.8309520  0.6403896
1
  • If the l statnds for the 'k' argument, there would be only two column output. Commented Feb 28, 2018 at 4:29

2 Answers 2

2

If we have to apply the 'k' for multiple columns, pass the columns in a list

res <- do.call(cbind, Map(function(l, k) rollmean(datt[,k], l, fill = NA), 
           1:2, list(c("x", "x2")))) 

However, we don't an extra argument as the need is for looping the k argument and the subset of data remains the same

do.call(cbind, lapply(1:2, rollmean, x = datt[c("x", "x2")], fill = NA))
Sign up to request clarification or add additional context in comments.

3 Comments

Thanks! However, I need to retain the l-1 because I lag the rollmean by 1.
@Vedda Ok, then you can remove the fill = NA and use your rep(NA, l-1)
In rollapply the width= can be a one component list containing a vector of offsets. This would avoid the rep. I have shown that in my revised answer but that approach could be incorporated here too.
2

Create a grid 4x2 grid of the 4 combinations of l and k and then mapply over that. Note that we can simplify fun slightly using fill = NA . Note that the width argument of list(1:l) means pass offsets 1 through l to the mean. Offset 1 is the next value and offset 2 is the value after the next value.

fun <- function(l, k) rollapply(datt[, k], list(1:l), mean, fill = NA)
g <- expand.grid(l = 1:2, k = c("x", "x2"))
mapply(fun, g[[1]], g[[2]])

Update

Based on comments by poster clarifying intent changed rollmean to rollapply with indicated width.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.