I wonder whether R can do this:
I have several tens of folders on my C: drive within C:/Names. For simplicity sake, say there's only two called "Ben" and "Dave". Each one of these folders has several files.
I want R to create a list of those files for each folder and then assign the list the name of that folder. So the result would give me two separate objects something like:
Ben:
[1] "File1.csv" "File2.csv"
Dave:
[1] "File3.csv" "File4.csv
I feel like I'd have to loop it to do so but with my limited knowledge, not really sure how. I want to do this for all the folders within C:/Names and not just for the two in the example.
Is this what you are looking to do?
names <- "C:/Names"
folders <- list.dirs(path = names, full.names = F, recursive = F)
for (foldersA in folders){
assign(foldersA, list.files(paste(names, foldersA, sep="/")))
}
Generally it's a bad idea to create objects with arbitrary names because there's the possibility that one of the subfolders will have a name that isn't legal for an object in R, or overwrites an existing object. The more R-ish way to do that is to create a single list using:
input.names <- lapply(list.dirs("c:\\Names"),list.files)
then you can either loop over the elements of the list for further processing, or access individual elements as input.names$Dave
or input.names[["Dave"]]
.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.