R - How to avoid loop in list of files -
my current learning goal in r avoid for
loops. have list files in directory (or loops through directories) perform diverse operations on files.
one example of task following: have invoke system application called cdo
merge 2 files. syntax of command is, let's say: cdo merge input_file1 input_file2 output_file
.
my current r code looks this:
# set lists of files u.files <- c("uas_amon_access1-3.nc", "uas_amon_cmcc-cesm.nc", "uas_amon_cmcc-cesm.nc") v.files <- c("vas_amon_access1-3.nc", "vas_amon_cmcc-cesm.nc", "vas_amon_cmcc-cesm.nc") (i in 1:length(u.files)) { # set input file 1 use on cdo input1 <- paste(u.files[i], sep='') # set input file 2 use on cdo input2 <- paste(v.files[i], sep='') # set output file use on cdo output <- paste('output_', u.files[i], sep='') # assemble command string comm <- paste('cdo merge', input1, input2, output, collapse='') # submit command system(comm) }
which works ok although not good.
however, times hear people saying for
loops in r slow , should avoided as possible.
is there way avoid loops , make code more efficient/legible in cases this?
this more r-idiomatic:
u.files <- c("uas_amon_access1-3.nc", "uas_amon_cmcc-cesm.nc", "uas_amon_cmcc-cesm.nc") v.files <- c("vas_amon_access1-3.nc", "vas_amon_cmcc-cesm.nc", "vas_amon_cmcc-cesm.nc") output <- paste('output_', u.files, sep='') comm <- paste('cdo merge', u.files, v.files, output) lapply(comm,system)
remember functions vectorized in r, don't have call paste
each iteration in loop. @ end obtain vector of commands , execute 1 one through lapply
in last line.
Comments
Post a Comment