0

I have a list of dataframes "ldf" and want to keep specific columns in each df of this list (those columns have the same name in each df)

I tried it like this which obviously failed,..

   newList <-
   lapply(names(ldf), function(i){
       x <- ldf[[ i ]]
       x <- x[c("Var1", "Var2")]
     })

Example:

 ldf <- list(data.frame(a = 1:5, b = 1:5, c = 1:5), data.frame(a = 1:5, b      = 1:5, c = 1:5))

When only keeping Var1 and Var2 the new list should be:

 list(data.frame(a = 1:5, b = 1:5), data.frame(a = 1:5, b = 1:5))
yasel
  • 433
  • 3
  • 13
  • 4
    Try iterating over the data frames in a list (not their names) with `foo <- list(mtcars, mtcars);lapply(foo, function(x) x[, c("mpg", "cyl")])` – pogibas Jan 08 '19 at 14:52
  • This `lapply(ldf, "[", c("a", "b"))` ? – Ronak Shah Jan 08 '19 at 14:56
  • Thanks PoGibas that works! Ronak Shah your approach seems to delete the data frames completly – yasel Jan 08 '19 at 15:01
  • It returns me list of 2 dataframes with `a` and `b` columns selected in each and actually it's the same approach as @PoGibas' . – Ronak Shah Jan 08 '19 at 15:05

0 Answers0