r - Apply function to columns in a list of data frames and append results -


i want apply function list of data frames. function takes elements 2 columns in each data frame adds them , adds output each data frame in new column.

create dummy data:

df.1 <- data.frame(data=cbind(rnorm(5, 0), rnorm(5, 2), rnorm(5, 5))) df.2 <- data.frame(data=cbind(rnorm(5, 0), rnorm(5, 2), rnorm(5, 5)))  names(df.1) <- c("a", "b", "c") names(df.2) <- c("a", "b", "c")  ls.1<- list(df.1,df.2) names(ls.1) <- c("cat", "dog") ls.1 

have @ data:

> ls.1 $cat                  b        c 1 0.7031868 1.730499 4.286386 2 0.1527551 2.794084 4.348707 3 1.1151157 0.154562 4.647605 4 0.5786497 1.407386 4.118078 5 0.9223104 2.995469 5.065981  $dog                     b        c 1  0.04024872 1.6760609 5.013490 2  0.18095899 2.1015250 3.452313 3 -0.86588484 2.1371948 6.389203 4 -0.39499567 0.5996709 5.399724 5 -1.31850123 3.0058084 5.530989 

pseudo code of want do:

 my.fun <- function(b, c) {   out.put <- b + c   ls.1[i]$d <- out.put } 

what want output like:

> ls.1 $cat                  b        c        d 1 0.7031868 1.730499 4.286386 6.689551 2 0.1527551 2.794084 4.348707 5.553838 3 1.1151157 0.154562 4.647605 8.526398 4 0.5786497 1.407386 4.118078 5.999395 5 0.9223104 2.995469 5.065981 8.536797  $dog                     b        c        d 1  0.04024872 1.6760609 5.013490 6.689551 2  0.18095899 2.1015250 3.452313 5.553838 3 -0.86588484 2.1371948 6.389203 8.526398 4 -0.39499567 0.5996709 5.399724 5.999395 5 -1.31850123 3.0058084 5.530989 8.536797 

i think should achievable mapply or similar i cannot figure out....

lapply works fine here. note return(x) needed here, otherwise return new vector.

res <- lapply(ls.1, function(x){  x$d <- x$b + x$c  return(x) }) 

Comments

Popular posts from this blog

node.js - Node js - Trying to send POST request, but it is not loading javascript content -

javascript - Replicate keyboard event with html button -

javascript - Web audio api 5.1 surround example not working in firefox -