##this function imports multiple csv files in the working directory and stops if column order does not match

##Step1 set working directory
setwd()

#Step2 read in all the file names in the working directory
files<-dir()

#Step3 - compiles a vector with the names of ALL FILES WITH "PRIMARY" in the file name. you must make sure that the files you want to read in have  primary in the name
primary.list<-files[grep("primary",files)]

#Step4 -The function, "dataMerge" take a list of text strings that correspond to the files that you want to read in and combine.  If the column names or order do not match, the function will stop and return an error message.  Otherwise it will return a single file with all of the merged rows. 

dataMerge<-function(FILES){

	rawData<-read.csv(FILES[1],header=TRUE,as.is=TRUE)
	inOrder<-NULL
	temp<-NULL

for(i in 2:length(FILES)){	
	temp<-read.csv(FILES[i],as.is=TRUE,header=TRUE)
	inOrder<-all.equal(names(rawData),names(temp))
	if(inOrder!=TRUE){
		print(paste("columns do not match in",FILES[i]))
		return(NULL)
		}
	rawData<-rbind(rawData,temp)	
	}

return(rawData)
	
}


#Step 5. create a full data file called "raw" using the dataMerge function & write it as a CSV in your working directory.
raw<-dataMerge(primary.list)
write.csv(raw,file="raw.csv")
