R lapply从数据帧列表中删除列

时间:2020-09-21 13:42:16

标签: r subset lapply

我正在尝试使用lapply和以下代码从数据帧列表中删除单个列(想同时从df1和df2中删除列名“ ID”)。通过命令提示符运行时,我收到以下错误消息:

eval(substitute(select),nl,parent.frame())中的错误: 找不到对象“ ID” 调用:lapply-> FUN-> subset.data.frame-> eval-> eval

关于代码为什么会产生错误的任何想法?

df1 <- data.frame(
 "Qty" = c(15,29,12,53),
 "Type"   = c("A","B","B","E"),
 "ID"   = c("x123","y121","x556","y119"))

df2 <- data.frame(
 "Qty" = c(5,92,25,31),
 "Type"   = c("I","L","Z","K"),
 "ID"   = c("p433","q232","y344","l598"))

df_list <- mget(ls(pattern= "^df"))

df_list <- lapply(df_list, function(x) subset.data.frame(x, select=-c(ID)))

list2env(df_list, .GlobalEnv)

2 个答案:

答案 0 :(得分:2)

尝试这种dplyr方法:

library(dplyr)         
#Data
df1 <- data.frame(
  "Qty" = c(15,29,12,53),
  "Type"   = c("A","B","B","E"),
  "ID"   = c("x123","y121","x556","y119"))

df2 <- data.frame(
  "Qty" = c(5,92,25,31),
  "Type"   = c("I","L","Z","K"),
  "ID"   = c("p433","q232","y344","l598"))

df_list <- mget(ls(pattern= "^df"))

df_list <- lapply(df_list, function(x) {x <- x %>% select(-ID)})

list2env(df_list, .GlobalEnv)

输出(将释放到环境中):

df_list
$df1
  Qty Type
1  15    A
2  29    B
3  12    B
4  53    E

$df2
  Qty Type
1   5    I
2  92    L
3  25    Z
4  31    K

答案 1 :(得分:1)

Base R解决方案:

# Safer, directly specifying the name: 
Map(function(x){x[,names(x) != "ID"]}, df_list)

# If the data.frames have the same column order: 
lapply(df_list, "[", 1:2)