Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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.

like image 797
code123 Avatar asked Apr 08 '26 06:04

code123


1 Answers

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)
like image 118
tcash21 Avatar answered Apr 10 '26 00:04

tcash21



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!