Neotropical bat risk assessments
2018-Apr-19 11:45 UTC
[R] Syntax for capturing and writing file names
Hi all, I am looking for syntax to read a list of *txt files, (loop through?) each with a different data content but same fields, then run lines of code to produce summary stats (I have working code for this) and add the matching data file name when writing the results of a line of R code.?? Suggestions on any package vignettes that may be useful welcomed. My manual code for this is below and need to understand how to have the "DataFile" name changed to match the name of each data file as it is read and processed. *write.csv(BatStats,file="C:\\=Bat data working\\Acoustic Parameters\\DataFile_Stats.csv")* -- Bruce W. Miller, PhD. Neotropical bat risk assessments Conservation Fellow - Wildlife Conservation Society If we lose the bats, we may lose much of the tropical vegetation and the lungs of the planet Using acoustic sampling to identify and map species distributions for >25 years. Providing free Interactive identification keys and call fact sheets for the vocal signatures of New World Bats [[alternative HTML version deleted]]
Hello, You can process several files at a time with repeated use of *appy functions. Something like the following (not tested). # This first instruction may not be needed old_dir <- setwd("path/to/txt/files") # Get the filenames in a vector and read them in txt_files <- list.files(pattern = ".*\\.txt") txt_list <- lapply(txt_files, read.table, args) In the above lapply command, args are the arguments to read.table. For instance, header = TRUE, stringsAsFactors = FALSE, etc. Now put your summary stats code in a function and run it through the data.frames in the list. Then save the results as csv files. stats_list <- lapply(txt_list, summary_stats_function) csv_files <- sub("txt", "csv", txt_files) lapply(seq_along(csv_files), function(i) write.csv(stats_list[[i]], csv_files[i])) setwd(old_dir) # reset, if needed Hope this helps, Rui Barradas On 4/19/2018 12:45 PM, Neotropical bat risk assessments wrote:> Hi all, > > I am looking for syntax to read a list of *txt files, (loop through?) > each with a different data content but same fields, then run lines of > code to produce summary stats (I have working code for this) and add the > matching data file name when writing the results of a line of R code. > Suggestions on any package vignettes that may be useful welcomed. > > My manual code for this is below and need to understand how to have the > "DataFile" name changed to match the name of each data file as it is > read and processed. > > *write.csv(BatStats,file="C:\\=Bat data working\\Acoustic > Parameters\\DataFile_Stats.csv")* >