Randy Minder
Randy Minder

Reputation: 48432

Appending a single variable from multiple files to a data frame or other object type

I'm just learning R. I have 300 different files containing rainfall data. I want to create a function that takes a range of values (i.e., 20-40). I will then read csv files named "020.csv", "021.csv", "022.csv" etc. up to "040.csv".

Each of these files has a variable named "rainfall". I want to open each csv file, extract the "rainfall" values and store (append) them to some sort of object, like a data frame (maybe something else is better?). So, when I'm done, I'll have a data frame or list with a single column containing rainfall data from all processed files.

This is what I have...

rainfallValues <- function(id = 1:300) {
    df = data.frame()

      # Read anywhere from 1 to 300 files
    for(i in id) {
          # Form a file name
        fileName <- sprintf("%03d.csv",i)

        # Read the csv file which has four variables (columns). I'm interested in
        # a variable named "rainfall".
        x <- read.csv(fileName,header=T)

        # This is where I am stuck. I know how to exact the "rainfall" variable values from
        # x, I just don't know how to append them to my data frame.
    }
}

Upvotes: 1

Views: 238

Answers (1)

lmo
lmo

Reputation: 38510

Here is a method using lapply that will return a list of rainfalls

rainList <- lapply(id, function(i) {
       temp <- read.csv(sprintf("%03d.csv",i))
       temp$rainfall
})

To put this into a single vector:

rainVec <- unlist(rainList)

comment
The unlist function will preserve the order that you read in the files, so the first element of rainVec will be the first observation of the first rainfall column from the first file in id and the second element the second observation in that files and so on to the last observation of the last file.

Upvotes: 3

Related Questions