How do you use sapply() with a "list" that includes two columns of data?
I am currently using sapply to call a weighted mean function that takes two inputs, a date and a date frame of multiple values per date,
sapply(unique(sort(d$Date, decreasing=TRUE)), WeightedMean, data=d))
WeightedMean <- function(date, data) {...}
but I would like to update this function to take three inputs.  I have created the code below, but am unable to reference both inputs in my WeightedMean function,
sapply(unique(d[order(d$Date, d$Id, decreasing=TRUE), c("Date", "Id")]), 
    WeightedMean, data=d)
WeightedMean <- function(date, id, data) {...}
Note that the WeightedMean function will filter the data by date and id and then calculate a summary value.  Is there a way I can update the above code to pass two开发者_如何学C parameters to the function?
You can use mapply instead if sapply.  (The m means "multiple arguments".)
ordered_data <- unique(d[order(d$Date, d$Id, decreasing = TRUE), c("Date", "Id")])
with(ordered_data, mapply(WeightedMean, Date, Id))
By using an anonymous function.
You don't provide a working example, so the following code is untested but should work:
sapply(unique(d[order(d$Date, d$Id, decreasing=TRUE), c("Date", "Id")]), 
    function(x){WeightedMean(x$Date, x$Id, data=x)})
 
         加载中,请稍侯......
 加载中,请稍侯......
      
精彩评论