繁体   English   中英

当每个 dataframe 中不存在所有这些列时,如何从数据框列表中删除特定列 [重复]

[英]How to remove specific columns from a list of dataframes when all of these columns do not exist in each dataframe [duplicate]

这是一个示例数据集:

dat1 <- structure(list(id = 1:3, des.1 = 4:6, x = 7:9, not = 10:12), class = "data.frame", row.names = c(NA,-3L))
dat2 <- structure(list(id = 1:3, descript = 4:6, y = 7:9, yes = 10:12), class = "data.frame", row.names = c(NA,-3L))
dat3 <- structure(list(id = 1:3, description = 4:6, x = 7:9, X4 = 10:12), class = "data.frame", row.names = c(NA,-3L))
dat_list <- list(dat1, dat2, dat3)

例如,如果我想在这个数据帧列表中删除所有名为 x 和 X4 的列,我可以这样做 - 访问每个包含这些列的 dataframe 并像这样删除它们:

dat_list[[1]] <- dat_list[[1]] %>% select(-x)
dat_list[[3]] <- dat_list[[3]] %>% select(-c("x", "X4"))

但是我想知道是否有一种方法可以在整个列表中执行此操作 - 请记住,其中一些列将不存在于列表中的每个 dataframe 中。

谁能想到一种方法可以删除此列表中所有数据帧中所有名为 c("x", "X4") 的列?

一种方法是:

library(tidyverse)
map(dat_list, function(xx) xx %>% select(any_of(c("x", "X4"))))
# [[1]]
#   x
# 1 7
# 2 8
# 3 9

# [[2]]
# data frame with 0 columns and 3 rows

# [[3]]
#   x X4
# 1 7 10
# 2 8 11
# 3 9 12

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM