Import multiple files into r as separate dataframes using for loop and assign
13:17 29 Mar 2026

Before I start my question I want to acknowledge that there are numerous discussions on this topic on stack overflow, however, I gave the codes a try and am still running into a wall. It is also required that I use base r functions only.

I have 12 files saved in different folders, ie. each file has a separate file path. I have successfully created a vector for the 12 paths used to access the files using a for loop and paste0(). I have also created a vector to simplify the name of each data frame (once imported) ie. subj1_act1, rather than the long file path name.

My issue is that I cannot read the values from each file successfully into separate dataframes and then assign each dataframe a simplified name.

Code (1)

Produces 12 dataframes with the correct variable name, however, the data values within each data frame are all the same (ie the values from the last df - subj3 act4).

subject <- c(1,1,1,1,2,2,2,2,3,3,3,3)
activity <- 1:4


    for (i in activity) {
      for (j in subject) {
    # setting the paths to each file
      file_paths <- paste0 (
      "Data-Assignment1/Subj", subject, "/subj", subject, "_act", activity, ".txt"
    )
     
    # generate suitable variable name for each dataframe  
    variable_name <- paste0 ("subj", subject, "_act", activity)
    
   }
  }
for (g in variable_name) {
for (h in file_paths) {
  # load files into r as dataframes
  df <- read.csv (
    (h), 
    header=FALSE)
  # assign each variable name to each dataframe accordingly
  assign(g, df)
  }
}

In code (2)

Dataframes and data values are correct, however, the dataframes are named by each of their individual file paths rather than the simplified variable name.

The reason we need to keep it this way is because we are later going to be doing more work within each dataframe and will need to able to refer to each df using for loops.

Any help is greatly appreciated!

r