Home > Back-end >  A function to select specific columns in a list of dataframes : RSTUDIO
A function to select specific columns in a list of dataframes : RSTUDIO

Time:09-26

Let's say I have a list of datasets with the same variables but with different values (In this example and to make it easy for me I am using the Salaries dataframe 3 times to create the list L but it can be any list of dataframes of the same variables with different values)


library(carData)

library(datasets)

L = list(Salaries,Salaries,Salaries)


Let's say I wish to select the first, the second and the sixth columns in this list of dataframes. How can I handle that ? Thanks.

CodePudding user response:

A tidyverse approach could look as follows (tested using mtcars):

library(dplyr)
library(purrr)

map(L, ~ select(., c(1, 2, 6)))

# [[1]]
#                      mpg cyl    wt
# Mazda RX4           21.0   6 2.620
# Mazda RX4 Wag       21.0   6 2.875
# Datsun 710          22.8   4 2.320
# Hornet 4 Drive      21.4   6 3.215
# Hornet Sportabout   18.7   8 3.440
# Valiant             18.1   6 3.460
# Duster 360          14.3   8 3.570
# Merc 240D           24.4   4 3.190
# Merc 230            22.8   4 3.150
# Merc 280            19.2   6 3.440

Data

L <- list(mtcars, mtcars, mtcars)

CodePudding user response:

If all the datasets in the list return the same subset of columns

lapply(L, `[`, c(1, 2, 6))
  • Related