Skip to content

Instantly share code, notes, and snippets.

@johnDorian
Created February 2, 2015 09:42
Show Gist options
  • Save johnDorian/1794ed9b69f5d6c5a587 to your computer and use it in GitHub Desktop.
Save johnDorian/1794ed9b69f5d6c5a587 to your computer and use it in GitHub Desktop.
An example to create, load, manipulate and save multiple csv files with R
### create some fictional data
dir.create("tmp")
setwd("tmp")
for(i in 1:10){
tmp_file <- data.frame(x=1:100, y=rnorm(100), z = rnorm(100))
tmp_file_name <- paste0(paste(letters[sample(1:24, 10)], collapse= ""), ".csv")
write.csv(tmp_file, tmp_file_name, row.names= FALSE)
}
### The actual script
fileNames<-list.files()
my.data <- list()
for (i in 1:length(fileNames)){
my.data[[i]] <- read.csv(fileNames[[i]],header=T)
}
## Create a function to do the job you want
write_indundated_file <- function(data_file, file_name){
## Calculate everything you want to
non_inundated <- data_file[,2]/10000
inundated <- data_file[,3]/10000
Total_area <- non_inundated+inundated
inundated_percent <- inundated/Total_area*100
tmp <- data.frame(non_inundated, inundated, Total_area, inundated_percent)
write.csv(tmp, file = file_name, row.names=FALSE)
}
for(i in 1:length(fileNames)){
write_indundated_file(my.data[[i]], fileNames[[i]])
}
## load the files and check that they have been modified correctly
for (i in 1:length(fileNames)){
my.data[[i]] <- read.csv(fileNames[[i]],header=T)
}
head(my.data[[1]])
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment