I have a list of data.frames, and would like to operate on their columns, using various weights.
For example, subtracting the first columns from the second column (solved, see below); or subtracting the first and third from twice the second (unsolved).
Thanks to the generous help obtained in response to this question, I have a solution to the the problem in two dimensions without weights using Reduce.
I would like to have the flexibility to operate with weights – and in higher dimesions.
What I have so far is:
priceList <- data.frame(aaa = rnorm(100, 100, 10), bbb = rnorm(100, 100, 10),
ccc = rnorm(100, 100, 10), ddd = rnorm(100, 100, 10),
eee = rnorm(100, 100, 10), fff = rnorm(100, 100, 10),
ggg = rnorm(100, 100, 10)
)
colDiff <- function(x)
{
Reduce('-', rev(x))
}
tradeLegsList <- combn(names(priceList), 3, function(x) priceList[x], simplify = FALSE)
tradeList <- lapply(tradeLegsList, colDiff)
From what I can tell, Reduce is not designed to take multiple arguments.
I can do this the long way with 2* tradeLegsList[[1]]$bbb - tradeLegsList[[1]]$aaa - tradeLegsList[[1]]$ccc, and some loops, but it doesn’t seem like the R way.
Is there a way to pass in a weight vector?
Ideally, I would to pass an argument such as w = c(-1, 2, -1) to the colDiff (or Reduce) function … or something similar.
True,
Reduceis not geared to allow multiple arguments, just two for each reduction. Therefore it is easiest to premultiply the elements in the list you areReduce-ing.Below is a solution that does this using
mapplywithin yourcolDifffunction definition.Change your definifion of colDiff to allow a weight vector, and apply this using
mapplywith
SIMPLIFY = F.EDIT
In light of the comments, weighting depends on the number of columns and there being no need for the
revThe weighting by length
Then something like this would work
you could also keep with the functional programming theme and use
Mapwhich is a simple wrapper formapplywithSIMPLIFY = Fyou could also prefine the weighting within the function colDiff (which may be easier).
weighting[[2]]is weighting for when there are 2 columns,weighting[[3]]when there are 3.