[R] Syntax for capturing and writing file names

Rui Barradas ru|pb@rr@d@@ @end|ng |rom @@po@pt
Thu Apr 19 17:25:28 CEST 2018


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")*
>




More information about the R-help mailing list