How to delete columns while looping over data frames?

Viewed 802

I have a number of data frames that all have a column with the same name; and I would like to loop over all the data frames to delete the column.

As an example :

> df1
  a b
1 1 2
2 1 2
3 1 2

> df2
  a c
1 1 3
2 1 3
3 1 3

I also have a list of all the data frame names :

> df.list
[[1]]
[1] "df1"

[[2]]
[1] "df2"

If I do df1$a<-NULL, column a is deleted.

I would like to delete column a in both dfs, this is what I tried :

library(dplyr)

make.null<-function(x) {
        x<-NULL
      }

lapply(df.list, function(x) {
      get(x) %>% select(starts_with("a")) %>% make.null()

       })

I also tried :

 lapply(df.list, function(x) {
      get(x) %>% select(-starts_with("a"))

       })

The console output from the last example is

[[1]]
  b
1 2
2 2
3 2

[[2]]
  c
1 3
2 3
3 3

but the data frames still have a as a column :

 > df1
  a b
1 1 2
2 1 2
3 1 2

So, how could I get the column to be deleted in all the data frames from the list ?

2 Answers

Since you have access to tidyverse, here is an example using lapply and select

library(tidyverse)

list_1 <- lapply(1:3, function(i)(tibble(a = sample(1000),
       c = sample(1000)))) ##Creates list of data frames

new_list <- lapply(list_1, function(i) i %>% select(-c)) ##loops through and remove c variable
new_list


##Using a for loop (not as efficient)
new_list2 <- NULL

for(i in 1:length(list_1)){
  new_list2[[i]] <- list_1[[i]] %>% select(-c)
}

new_list2

In a tidyverse and purrr style,

library(tidyverse)
library(data.table)
#> 
#> 载入程辑包:'data.table'
#> The following objects are masked from 'package:dplyr':
#> 
#>     between, first, last
#> The following object is masked from 'package:purrr':
#> 
#>     transpose
df1 <- 
    data.table(a=rep(1,3),b=2)
df2 <- 
    data.table(a=rep(1,3),c=3)
list_tbl <- 
    list(df1,df2) %>% 
    map(~select(.,-a))
    # this is mapping function like loops
list_tbl
#> [[1]]
#>    b
#> 1: 2
#> 2: 2
#> 3: 2
#> 
#> [[2]]
#>    c
#> 1: 3
#> 2: 3
#> 3: 3

Created on 2018-11-08 by the reprex package (v0.2.1)

Related