Search code examples
rtransformationdata-preprocessingdata-munging

How to apply the equivalent of standard sub setting operations but to a list of dataframes instead of to a single dataframe


I have a set of 40 different datasets within a file folder which I have loaded into my WorkSpace in RStudio with:

datasets <- lapply(filepaths_list, read.csv, header = FALSE)

This object datasets is a list of 40 dataframes. I would like to run code which does the same as the following line of code does when the object is a single dataframe instead:

All_sample_obs <- datasets[-1:-3,]

From there, I would likewise like to find ways to find iterative versions of the following further 3 simple pre-processing transformation steps:

All_sample_obs <- lapply(All_sample_obs, as.numeric)
All_sample_obs <- as.data.frame(All_sample_obs)
All_sample_obs <- round(All_sample_obs, 3)

Solution

  • The following should do what you are looking for:

    All_sample_obs <- lapply(datasets, function(i) {i[-1:-3, ]})
    
    All_sample_obs <- lapply(All_sample_obs, \(X) { lapply(X, as.numeric) })
    All_sample_obs <- lapply(All_sample_obs, function(i) { as.data.frame(i) })
    All_sample_obs <- lapply(All_sample_obs, \(X) { round(X, 3) })
    

    I included two solutions with each of the two common syntaxes used for lapplies, both are valid.