在lapply()
向量上使用时,结果列表的每个元素都没有名称,而只有一个索引:
library(dplyr)
vector = c("df1", "df2")
df1 = data.frame(a = rnorm(5), b = rnorm(5, sd = 1.1))
df2 = data.frame(a = rnorm(5), b = rnorm(5, sd = 1.1))
lapply(vector, function(x){
x = get(x) %>%
mutate(c = a+b)
})
#> [[1]]
#> a b c
#> 1 -0.4098768 1.6712810 1.2614041
#> 2 0.7101722 -0.1025184 0.6076538
#> 3 -0.6696859 0.5690932 -0.1005928
#> 4 1.1642214 -0.4660378 0.6981836
#> 5 -0.5158280 1.4574039 0.9415759
#>
#> [[2]]
#> a b c
#> 1 0.91047848 -1.308707 -0.3982281
#> 2 1.87336493 -1.429567 0.4437977
#> 3 0.54171333 1.849589 2.3913028
#> 4 -0.02978158 2.500763 2.4709817
#> 5 1.49926589 1.602463 3.1017284
应用列表时确实有名称:
list = list(
df1 = data.frame(a = rnorm(5), b = rnorm(5, sd = 1.1)),
df2 = data.frame(a = rnorm(5), b = rnorm(5, sd = 1.1))
)
lapply(list, function(x){
x = x %>%
mutate(c = a+b)
})
#> $df1
#> a b c
#> 1 0.8228400 -2.5232496 -1.70040963
#> 2 0.3890213 -0.4349408 -0.04591949
#> 3 0.5084719 1.4089123 1.91738415
#> 4 0.2533964 -0.7379615 -0.48456516
#> 5 -0.2474338 1.0520906 0.80465685
#>
#> $df2
#> a b c
#> 1 0.1376350 -1.32304077 -1.1854058
#> 2 0.1314702 1.14775210 1.2792223
#> 3 0.9757047 -1.24806193 -0.2723573
#> 4 -0.5118045 0.09277009 -0.4190344
#> 5 -0.1631715 -0.47573087 -0.6389024
有没有简单的方法可以将vector元素用作结果列表名称?
您可以先命名向量
vector = c("df1", "df2")
names(vector) <- vector # <-- here
df1 = data.frame(a = rnorm(5), b = rnorm(5, sd = 1.1))
df2 = data.frame(a = rnorm(5), b = rnorm(5, sd = 1.1))
lapply(vector, function(x){
x = get(x) %>%
mutate(c = a+b)
})
# $df1
# a b c
# 1 -0.36671838 0.8733203 0.5066019
# 2 -0.05029296 -0.8823471 -0.9326401
# 3 0.54252815 -0.2087211 0.3338071
# 4 -1.16789527 0.2598863 -0.9080090
# 5 -0.80664672 -0.4968422 -1.3034889
#
# $df2
# a b c
# 1 0.9042845 1.2978663 2.2021508
# 2 -0.3848533 -0.4563623 -0.8412156
# 3 -1.1681873 1.3224087 0.1542215
# 4 1.4872564 -2.0281272 -0.5408708
# 5 -0.2717229 -0.3780464 -0.6497694
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句