0

I have data from 2011 to 2016 and each is located in a separate folder as for example in 2011 folder, the 2011 data are located and in 2012, the data for 2012 and the same rule applies to data from 2013 to 2016.

I would like to do a for loop. So is there a way that I can do? Thank you for your help and consideration.

Instead of doing like this:

data11<- 
  read.delim("./Vegetation_Processed/2011/ForageMass_2011_all.dat", header = TRUE, sep ="",stringsAsFactors = FALSE)
data12<- 
  read.delim("./Vegetation_Processed/2012/ForageMass_2012_all.dat", header = TRUE, sep ="",stringsAsFactors = FALSE)
data13<- 
  read.delim("./Vegetation_Processed/2013/ForageMass_2013_all.dat", header = TRUE, sep ="",stringsAsFactors = FALSE)
data131 <-  
  read.xlsx("./Vegetation_Raw/2013/ForageAnalysis_2013_all.xlsx",sheetIndex=1)

I would like to have a loop and combined all the data in the same file.

1 Answers1

0

If the columns are all the same you can use rbind to join data.frames into a single object:

d1 <- data.frame("this"=c(1,2,3,4),"that"=c(4,5,6,7))
d2 <- data.frame("this"=c(11,12,13,14),"that"=c(41,51,61,71)) 
d3 <- data.frame("this"=c(111,112,113,114),"that"=c(411,511,611,711))

data1112 <- rbind(d1, d2, d3)

If this does not work please include a reproducible small excerpt of the data and any errors.

bruce.moran
  • 347
  • 2
  • 10
  • For combination, I can use rbind but for reading individual datasets from each folder, how do I do that? We first need to define d1,d2 and d3 but instead of using read.delim for each individual file, I would like to get a for loop because I have to read 9 dat files. – Sonisa Sharma Feb 01 '19 at 15:56
  • @SonisaSharma ... there are many, many examples of reading data from text files using `list.files` into list of data frames for final rbind: `do.call(rbind, my_list_of_dfs)`. This is one of the most [common R questions](https://stackoverflow.com/questions/tagged/r+csv) on StackOverflow. See canonical question: [How to import multiple .csv files at once?](https://stackoverflow.com/q/11433432/1422451) – Parfait Feb 01 '19 at 16:17
  • Thank you so much for helping me out. I hope to make progress. – Sonisa Sharma Feb 01 '19 at 16:36