jesstme
jesstme

Reputation: 624

For loop to eliminate columns in multiple dfs

I've got about 10 dataframes. For the example, here are two:

name <- c("A", "B", "C")
name.footnote <- c("this", "that", "the other")
class <- c("one", "two", "three")
class.footnote <- c("blank", "blank", "blank")

df1 <- data.frame(name, name.footnote, class, class.footnote)
df2 <- data.frame(name, name.footnote, class, class.footnote)

When I eliminate columns from them one at a time, my code works fine.

library(dplyr)
df1 <- select(df1, -ends_with("footnote"))

I'd like to write a loop to process both dfs with less code, but can't get my loop working right. I keep getting the same error message:

Error in UseMethod("select_") :   no applicable method for 'select_'
 applied to an object of class "character".

See a few of the many loop codes I've tried, below. What am I missing?

listofDfs <- list("df1","df2")

1.

lapply(listofDfs, function(df){
  df <- select(df, -ends_with("footnote"))
  return(df)
  }
)

2.

for (i in listofDfs){
  i <- select(i, -ends_with("footnote"))
}

Upvotes: 1

Views: 269

Answers (1)

Adam Spannbauer
Adam Spannbauer

Reputation: 2757

Try dropping the quotes when defining your list listofDfs <- list(df1,df2). As the error states, when you have the quotes the elements of your list are character instead of the data.frame that select() is expecting.

library(dplyr)

listofDfs <- list(df1,df2)

#using lapply
list_out1 <- lapply(listofDfs, function(df){
  df <- select(df, -ends_with("footnote"))
  return(df)
})

#using for loop
list_out2 <- vector("list", length(listofDfs))
for (i in seq_along(listofDfs)){
  list_out2[[i]] <- select(listofDfs[[i]], -ends_with("footnote"))
}

follow up per comment

you can use get and assign to work with your original character list and manipulate the dfs in your global environment while iterating.

listofDfs <- list('df1','df2')

invisible(lapply(listofDfs, function(i){
  df <- select(get(i, globalenv()), -ends_with("footnote"))
  assign(i, df, envir = globalenv())
}))

for (i in listofDfs){
  df <- select(get(i, globalenv()), -ends_with("footnote"))
  assign(i, df, envir = globalenv())
}

Upvotes: 2

Related Questions