[R] help with function calls
Naresh Gurbuxani
naresh_gurbuxani at hotmail.com
Sun Mar 27 17:46:12 CEST 2016
I have a data frame with with several columns of parameters and one column of function name which should be used with these parameters. My goal is to call the appropriate function for each row and summarize the results in a list or data frame. I can partition the data frame according to function name, then call each function at a time. Is there a more elegant way to achieve this result with one call only?
Below is an example. Here the functions are simple. It is possible to write a function that incorporates both the functions. It is not so easy in my actual task. My goal is to make one call and obtain res.df.
Thanks,
Naresh
sum.sq <- function(x) {return(sum(x^2))}
sum.cube <- function(x) {return(sum(x^3))}
input.df <- data.frame(x1 = c(1,2,3,4), x2 = c(2,3,4,5), x3 = c(3,4,5,6), method = c(rep("sum.sq", 2), rep("sum.cube", 2)), case = c("a", "b", "c", "d"))
library(plyr)
res.df1 <- ddply(subset(input.df, method == "sum.sq"), c("case"), function(df) {
x.vec <- c(df$x1, df$x2, df$x3)
return(data.frame(sum.power = sum.sq(x.vec)))
})
res.df2 <- ddply(subset(input.df, method == "sum.cube"), c("case"), function(df) {
x.vec <- c(df$x1, df$x2, df$x3)
return(data.frame(sum.power = sum.cube(x.vec)))
})
res.df <- rbind(res.df1, res.df2)
res.df <- merge(res.df, input.df[,c("method", "case")], by = "case")
More information about the R-help
mailing list