[英]R lapply to remove column from list of dataframes
I am trying to remove a single column from a list of dataframes using lapply with the below code (want to remove column name "ID" from both df1 and df2).我正在尝试使用 lapply 和以下代码从数据帧列表中删除单个列(想要从 df1 和 df2 中删除列名称“ID”)。 I receive the following error message when running through command prompt:通过命令提示符运行时,我收到以下错误消息:
Error in eval(substitute(select), nl, parent.frame()): object 'ID' not found Calls: lapply -> FUN -> subset.data.frame -> eval -> eval eval(substitute(select), nl, parent.frame()) 错误:object 未找到“ID” 调用:lapply -> FUN -> subset.data.frame -> eval -> eval
Any thoughts as to why the code produces an error?关于为什么代码会产生错误的任何想法?
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)
Try this dplyr
approach:试试这个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)
The output (which will be released to environment): output(将发布到环境):
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
Base R solutions:基地 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)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.