How to index (subset) over a list of data.frames

dataframe, lapply, list, r

Solution

Your code is perfectly good R. But you have two alternative options:

- Use an anonymous function - this is a general solution

- Use the `[` operator - specific to this case

Your original:

xx <- lapply(myList,removeCols,1:2)

An anonymous function:

yy <- lapply(myList, function(df, vec){df[,-vec]}, 1:2)

Use the `[` operator:

zz <- lapply(myList, "[", -(1:2))

These yield identical results

identical(xx, yy)
[1] TRUE

identical(xx, zz)
[1] TRUE

Problem

I got a list of several data.frames and I want to remove the first 2 columns from each of the data.frames. I did it as follows, but feel this could be more R-ish. ``` data(mtcars) data(iris) myList <- list(A = mtcars, B = iris) # helper function removeCols <- function(df,vec) { res <- df[,-vec] } lapply(myList,removeCols,1:2) ``` Obviously this does the job, but to me it seems like i must have missed something here (such as using an operator within lapply, cause it's technically a function too). However, the major disadvantage of this approach is that you need a little helper function for every little task you want to do to all elements of that list.

Original source