split into trials for multiple files

Hi,

Welcome to the RStudio community!

I'm not 100% sure what you're trying to do, but here is some code that might help:

library(tidyverse)
library(readxl)

#Ensures data frames can be merged without factor warnings
options(stringsAsFactors = F)

#Get the list of all files (should all have the same columns!)
allfiles <- list.files (path = "C:/Users/Daniela Canu/Documents/R/MS_Toolbox_Daniela/MS_Toolbox_Daniela/data", pattern = "*.xls", full.names=TRUE)

#Load all the files and merge them together
df <- map_df(allfiles, function(myFile){
  myData = read_excel(myFile) #load file with excel function
  fileName = str_match(myFile, "([^\\/]+).xls")[2] #extract the file name from the path
  cbind(fileName, myData) #add the file name to the data as first column
})

head(df)
  • First all xls files are found in your folder (make sure no other xls files are in there)
  • Then all files are loaded with the read_excel function
    • Using the map_df will merge all files into one big final data frame
    • I use regex to extract the file name from the path, and use it as a first column so you'll know which data came from which file in the final result
  • The resulting data frame has all files merged, with the first column as label. You can now proceed filtering or further analysis

Hope this helps,
PJ

PS: If you want to make sure people on this forum can help you out, make sure to create a reprex in future. A reprex consists of the minimal code and data needed to recreate the issue/question you're having. You can find instructions how to build and share one here:

1 Like