2

so I have 29 data files that I want to load into R. The files are called "1.csv", "2.csv" etc. all the way to 29. Here is the code depicting what I'm trying to do:

file.number <- c(1:29)
"the value in file.number".data <- read.csv("the value in file.number"".csv")

Basically I am looking for a way to load code based on a list, and label it accordingly. Is this possible?

Any help will be greatly appreciated!!!

3
  • 4
    setNames(lapply(paste0(1:29, ".csv"), read.csv), paste0(1:29, ".data")) might do it Oct 8, 2014 at 22:23
  • This worked quite nicely! Thank you! Oct 8, 2014 at 23:17
  • 1
    Glad it worked, I added it as an answer. Oct 8, 2014 at 23:21

2 Answers 2

4

This would probably work

dfList <- setNames(lapply(paste0(1:29, ".csv"), read.csv), paste0(1:29, ".data"))

Now you've got a named list of 29 data frames. Then you can access each individual data frame with the $ operator, e.g. dfList$"4.data". Note that you'll need quotes or backticks since you've chosen to begin the names with a digit. You can avoid that by using [[ to access the elements i.e. dfList[["4.data"]], or changing to different names such as paste0("data", 1:29), or any name that doesn't begin with a digit.

Another option would be Map

Map(read.csv, paste0(1:29, ".csv"))

This will automatically set the names to the names of the file being read i.e. 1.csv, 2.csv, etc. But again, backticks or quotes would be needed to access the elements with the $ operator because the names begin with digits.

1
listwithdfs <- lapply(1:29, function(x) read.csv(paste0(x, ".csv"))  )
names(listwithdfs) <- 1:29

better to only have one single object in workspace. now you can index with

listwithdfs[[13]]
3
  • I tried this, but for whatever reason it assumes there is a space between "1" and ".csv" "1 .csv". Oct 8, 2014 at 22:59
  • Setting the names as numbers is a bit pointless when you're just using the list index. Oct 8, 2014 at 23:09
  • @BrettCochrane Sounds like you used paste() instead of paste0(). If you use paste() you need to specify sep = "". Oct 8, 2014 at 23:23

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.