R 在现有列表上使用Lappy时保留原始列表项名称
我有三个数据帧存储在一个列表中,如下所示:R 在现有列表上使用Lappy时保留原始列表项名称,r,lapply,R,Lapply,我有三个数据帧存储在一个列表中,如下所示: dat <- list("grp_1" = data.frame(x = sample(1:100, 100, replace = T)), "grp_2" = data.frame(x = sample(1:100, 100, replace = T)), "grp_3" = data.frame(x = sample(1:100, 100, replace = T))) 如果数据帧名为grp_
dat <- list("grp_1" = data.frame(x = sample(1:100, 100, replace = T)),
"grp_2" = data.frame(x = sample(1:100, 100, replace = T)),
"grp_3" = data.frame(x = sample(1:100, 100, replace = T)))
如果数据帧名为grp_1或grp_2,我将对其进行过滤以仅保留前10行,否则,我将对其进行过滤以保留前20行
dat_new <- lapply(names(dat), function(x) {
if(x %in% c("grp_1", "grp_2")) {
dat[[x]] <- dat[[x]] %>%
slice(1:10)
} else {
dat[[x]] <- dat[[x]] %>%
slice(1:20)
}
})
我的函数执行正常,但由于某种原因,我在执行时丢失了列表元素名称,即输出是三个未命名数据帧的列表,而不是三个名为grp_1、grp_2和grp_3的数据帧
有人能告诉我如何修改上述代码,使缩短的数据帧保留其原始名称吗?只需添加名称:
names(dat)
# [1] "grp_1" "grp_2" "grp_3"
names(dat_new)
# NULL
names(dat_new) <- names(dat)
names(dat_new)
# [1] "grp_1" "grp_2" "grp_3"
设置名称的单向:n