Append data frames together in a for loop

后端 未结 8 1698
無奈伤痛
無奈伤痛 2020-11-28 19:21

I have a for loop which produces a data frame after each iteration. I want to append all data frames together but finding it difficult. Following is what I am

8条回答
  •  一生所求
    2020-11-28 20:05

    In the Coursera course, an Introduction to R Programming, this skill was tested. They gave all the students 332 separate csv files and asked them to programmatically combined several of the files to calculate the mean value of the pollutant.

    This was my solution:

      # create your empty dataframe so you can append to it.
      combined_df <- data.frame(Date=as.Date(character()),
                        Sulfate=double(),
                        Nitrate=double(),
                        ID=integer())
      # for loop for the range of documents to combine
      for(i in min(id): max(id)) {
        # using sprintf to add on leading zeros as the file names had leading zeros
        read <- read.csv(paste(getwd(),"/",directory, "/",sprintf("%03d", i),".csv", sep=""))
        # in your loop, add the files that you read to the combined_df
        combined_df <- rbind(combined_df, read)
      }
    

提交回复
热议问题