R Loop to Select Specific Columns from Multiple Dataframes

Viewed 894

I am trying to write a loop in R that will select the same specific column names in multiple data frames. The below code seems to achieve the desired output but the dataframes are not re-assigned. How can I re-assign the dataframes df1 and df2 to the lapply output?

 col1 <- c(1,2,3,4)
 col2 <- c("A","B","C","D")
 col3 <- c(4,15,"BLANK","ZZ")

 df1 <- data.frame(col1,col2, col3)

 col1 <- c(500,546,47,87)
 col2 <- c("E","L","J","U")
 col3 <- c(6,10,"F","R")

 df2 <- data.frame(col1,col2, col3)

 df_list <- list(df1,df2)

 lapply(df_list,function(x) {x<- x %>% select("col1","col2")} )
1 Answers

We can use a named list and then with list2env to update the objects in the global env (but, it is better to keep it in a list)

list2env(setNames(lapply(df_list, `[`, c("col1", "col2")),
         c("df1", "df2")), .GlobalEnv)
df1
#  col1 col2
#1    1    A
#2    2    B
#3    3    C
#4    4    D
df2
#  col1 col2
#1  500    E
#2  546    L
#3   47    J
#4   87    U

Instead of creating the 'df_list' by specifying list(df1, df2), we can have a named list by making use of mget

df_list <- mget(ls(pattern= "^df\\d+$"))

then, it is more easier

list2env(lapply(df_list, `[`, c("col1", "col2")), .GlobalEnv)
Related