R 当每个数据帧中不存在所有列时,如何从数据帧列表中删除特定列
以下是一个示例数据集:R 当每个数据帧中不存在所有列时,如何从数据帧列表中删除特定列,r,R,以下是一个示例数据集: 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.
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的列,我可以这样做-访问包含这些列的每个数据帧,然后像这样删除它们:
dat_list[[1]] <- dat_list[[1]] %>% select(-x)
dat_list[[3]] <- dat_list[[3]] %>% select(-c("x", "X4"))
然而,我想知道是否有一种方法可以在整个列表中实现这一点——请记住,这些列中的某些列不会存在于列表中的每个数据帧中
有人能想出一种方法来删除列表中所有数据帧中所有名为cx,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
一种方法是:
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
尝试lapplydat_列表,functionii[!namesi%在%c'x',X4']尝试lapplydat_列表,functionii[!namesi%在%c'x',X4']这是我会采取的方法,尽管由于OP需要除x和X4之外的所有列,所以您需要在任意列前面加一个感叹号:select!我错过了,好地方!这是我将采取的方法,但是由于OP需要除x和X4之外的所有列,所以您需要在any_of:select!前面加一个感叹号!我错过了,好地方!