我想将一个函数应用于数据框列表.该函数从每个数据框中的两列中获取元素,然后将输出添加到新列中的每个数据框.
创建虚拟数据:
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
Run Code Online (Sandbox Code Playgroud)
看看数据:
> 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
Run Code Online (Sandbox Code Playgroud)
我想做的伪代码:
my.fun <- function(b, c) {
out.put <- b + c
ls.1[i]$d <- out.put
}
Run Code Online (Sandbox Code Playgroud)
我希望输出看起来像:
> 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
Run Code Online (Sandbox Code Playgroud)
我认为应该可以通过mapply或类似的东西轻松实现,但我无法弄明白......
lapply这里运作正常.注意return(x)这里需要a ,否则我们只返回新的向量.
res <- lapply(ls.1, function(x){
x$d <- x$b + x$c
return(x)
})
Run Code Online (Sandbox Code Playgroud)