Matt Gossett
Matt Gossett

Reputation: 184

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

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)

Upvotes: 1

Views: 1743

Answers (2)

hello_friend
hello_friend

Reputation: 5788

Base R solutions:

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

Upvotes: 1

Duck
Duck

Reputation: 39595

Try this dplyr approach:

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

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

Upvotes: 5

Related Questions