code123
code123

Reputation: 2146

Apply multiple functions to two dataframes column-wise

Given the following sample data:

library(Metrics)

obs=data.frame(replicate(10,runif(100)))
pred=data.frame(replicate(10,runif(100)))

obs1=as.data.frame(lapply(obs, function(cc) cc[ sample(c(TRUE, NA), prob = c(0.85, 0.15), size = length(cc), replace = TRUE) ]))
pred1=as.data.frame(lapply(pred, function(cc) cc[ sample(c(TRUE, NA), prob = c(0.85, 0.15), size = length(cc), replace = TRUE) ]))

pred1[,1]=NA 

result=mapply(function(x, y) {if(all(is.na(y))) NA else mae(x, y, ), mse(x,y),rmse(x,y),se(x,y)
}, obs1,pred1,SIMPLIFY = F,USE.NAMES = TRUE)

I want to calculate say mae(obs1[,1],pred1[,1]) etc via mapply. How can I do the same for all other functions via a single call using base R functionsor plyr?

In the output, the rownames of resultare the column names of either obs1 or pred1 while the colnames are mae, mse,rmse,se etc.

Upvotes: 3

Views: 194

Answers (1)

tcash21
tcash21

Reputation: 4995

You have to write your own function to specify the various functions you'd like to apply:

 multi.fun <- function(x,y) {
   c(mae = mae(x,y), mse = mse(x,y))
 }

Then you can do:

obs=data.frame(replicate(10,runif(100)))
pred=data.frame(replicate(10,runif(100)))

obs1=as.data.frame(lapply(obs, function(cc) cc[ sample(c(TRUE, NA), prob =     c(0.85, 0.15), size = length(cc), replace = TRUE) ]))
pred1=as.data.frame(lapply(pred, function(cc) cc[ sample(c(TRUE, NA), prob =  c(0.85, 0.15), size = length(cc), replace = TRUE) ]))

mapply(multi.fun, obs1, pred1)

Upvotes: 1

Related Questions