Created
January 17, 2018 13:00
-
-
Save summerofgeorge/6bb8a4596d6830eea311f1e266e6d86a to your computer and use it in GitHub Desktop.
Loop through files in R and apply functions
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| #perform a function on each file | |
| #https://www.r-bloggers.com/perform-a-function-on-each-file-in-r/ | |
| setwd("H:/sample") | |
| list.files("H:/sample") | |
| fileNames<-Sys.glob("*.csv") | |
| fileNames | |
| for (fileName in fileNames) { | |
| # read data: | |
| sample <- read.csv(fileName, | |
| header = TRUE, | |
| sep = ",") | |
| # add more stuff here | |
| } | |
| for (fileName in fileNames) { | |
| # read old data: | |
| sample <- read.csv(fileName, | |
| header = TRUE, | |
| sep = ",") | |
| # add one to every widget value in every file: | |
| sample$Widgets <- sample$Widgets + 1 | |
| # overwrite old data with new data: | |
| write.table(sample, | |
| fileName, | |
| append = FALSE, | |
| quote = FALSE, | |
| sep = ",", | |
| row.names = FALSE, | |
| col.names = TRUE) | |
| } | |
| extension <- "csv" | |
| fileNames <- Sys.glob(paste("*.", extension, sep = "")) | |
| fileNumbers <- seq(fileNames) | |
| for (fileNumber in fileNumbers) { | |
| newFileName <- paste("new-", | |
| sub(paste("\\.", extension, sep = ""), "", fileNames[fileNumber]), | |
| ".", extension, sep = "") | |
| # read old data: | |
| sample <- read.csv(fileNames[fileNumber], | |
| header = TRUE, | |
| sep = ",") | |
| # add one to every widget value in every file: | |
| sample$Widgets <- sample$Widgets + 1 | |
| # write old data to new files: | |
| write.table(sample, | |
| newFileName, | |
| append = FALSE, | |
| quote = FALSE, | |
| sep = ",", | |
| row.names = FALSE, | |
| col.names = TRUE) | |
| } | |
| fileNames <- Sys.glob("*.csv") | |
| for (fileName in fileNames) { | |
| # read original data: | |
| sample <- read.csv(fileName, | |
| header = TRUE, | |
| sep = ",") | |
| # create new data based on contents of original file: | |
| allWidgets <- data.frame( | |
| File = fileName, | |
| Widgets = sum(sample$Widgets)) | |
| ##YOU could definitely use this for the SIC thing! | |
| # write new data to separate file: | |
| write.table(allWidgets, | |
| "Output/sample-allSamples.csv", | |
| append = TRUE, | |
| sep = ",", | |
| row.names = FALSE, | |
| col.names = FALSE) | |
| } |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment