0

I have a set of 125 .csv files that I want to combine into one data frame and file. Each csv file is one column of the data frame I ultimately want. I also need to add the site names at the beginning of the new data frame. The final result should look like this (with the rows all lined up, a 2x4 table in this example):

site species 1
cole 2
fillmore 4
species 2 species 3
1 2
6 3

I have gotten this far in the code:

# your text read in list of files
files<-list.files(path = 'C:\\Users\\rache\\...\\individual csv files\\test', pattern = ".csv")

#create dataframe with names of sampling points
data_cols <- read_csv("raw_abund_counts.csv")

bups_all<-as.data.frame(data_cols[,1])

#the loop is where ther are problems, all else works correctly.
# read in bup files and add to dataframe
bups_all <-for(i in 1:length(files)) {
  tmp<-read.csv(files[i])
  bups_all<-cbind(bups_all, tmp)
}

When my associate runs the loops, she said that it would sometimes drop a site from the model, resulting in one less than our expected total. However, when I try to run the loop the bups_all changes from a data frame with my list of sites, and becomes a value that is NULL. Running the code in the loop manually does indeed link up the site names and the first column of data as I expected. Any insight or help would be greatly appreciated!

MrFlick
  • 195,160
  • 17
  • 277
  • 295
Rach B.
  • 13
  • 3
  • 3
    You can probably use these methods https://stackoverflow.com/questions/23995384/read-and-rbind-multiple-csv-files but replace `rbind` with `cbind` or `bind_rows` with `bind_cols`. Note that a `for` loop in R always returns NULL so you never want to do `bups_all <-for(...) {...}` – MrFlick Mar 03 '23 at 22:42
  • Thank you for the suggestion. I tried the top recommendation on that thread, but I still just ended up with a NULL object. summary states: Length Class Mode 0 NULL NULL – Rach B. Mar 04 '23 at 01:43
  • Try ``bups_all <- do.call(cbind, lapply(files, function(file){ read.csv(file) }))`` – runr Mar 04 '23 at 01:50

0 Answers0