【问题标题】:How to remove specific columns from a list of dataframes when all of these columns do not exist in each dataframe [duplicate]当每个数据框中不存在所有这些列时,如何从数据框列表中删除特定列[重复]
【发布时间】:2020-06-26 10:09:37
【问题描述】:

这是一个示例数据集:

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"))

但是我想知道是否有办法在整个列表中执行此操作 - 请记住,其中一些列不会存在于列表中的每个数据框中。

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

【问题讨论】:

  • 试试lapply(dat_list, function(i)i[!names(i) %in% c('x', 'X4')])

标签: r


【解决方案1】:

一种方法是:

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

【讨论】:

  • 这是我将采取的方法,但由于 OP 想要所有列 except "x" 和 "X4",您需要在 @ 之前放置一个感叹号987654322@:select(!any_of(c("x", "X4")))
  • 啊,我错过了,好地方!
猜你喜欢
  • 2012-11-13
  • 2018-04-13
  • 2017-08-17
  • 1970-01-01
  • 2018-12-21
  • 2021-09-29
  • 1970-01-01
  • 2021-11-30
  • 2019-11-04
相关资源
最近更新 更多