I want to apply a function to a list of data frames. the function takes elements from two columns in each data frame adds them and then adds the output to each data frame in a 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 a look at the data:
> ls.1
$cat
a 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
a 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 what I want to do:
my.fun <- function(b, c) {
out.put <- b + c
ls.1[i]$d <- out.put
}
What I want the output to look like:
> ls.1
$cat
a 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
a 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 it should be easily achievable with mapply or something similar but I I cannot figure it out....
lapply
works fine here. Note that a return(x)
is needed here, otherwise we would just return the new vector.
res <- lapply(ls.1, function(x){
x$d <- x$b + x$c
return(x)
})
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With