i have a folder with multiple sub folders.
each subfolder has a csv file ending in chance_day_speed and also has a subject Id attached to the file name. eg 181523_chance_day_speed ... so subject id is 181523
- I want to extract all the files ending with "chance_day_speed" in each subfolder , attach the extracted subject_id (181523) in the file name to the record I extracted the file name from, then make a master file from all the extracted csv file .
How can I also do this in R ?
Thanks
CodePudding user response:
In R the following might work reading in the data, creating a new column subject_id
and then putting all data together in one data.frame named master
. Untested, since there are no data.
file_pattern <- "chance_day_speed\\.csv$"
fls <- list.files(pattern = pattern)
df_list <- lapply(fls, \(f) {
df <- read.csv(f)
df$subject_id <- sub("^(\\d ).*$", "\\1", f)
df
})
master <- do.call(rbind, df_list)
To write the data.frame master
to file, see write.csv
.