R: Working with named objects in a loop

我会带着你远行 2022-06-12 07:55 293阅读 0赞

R: Working with named objects in a loop

Leave a reply

Often I want to load, manipulate, and re-save a bunch of separate objects (e.g. a dozen or so SBE microCATs all strung out along a mooring line). To do this, I make use of the get(), assign(), and eval() functions in R. To start, I often define a vector of variable names, like:

  1. varNames <- c(mc100, mc200, mc300, mc500, mc750, mc900, mc1000, mc1500)

where the numbers in the name signify the nominal depth and the names themselves are the object names saved during a previous processing step. Then, I can loop through the instruments by doing:

  1. library(oce)
  2. for (i in seq_along(varNames)) {
  3. load(paste(varNames[i], '.rda', sep='')
  4. d <- get(varNames[i]) # copy the object to an object named `d`
  5. eval(parse(text=paste('rm(', varNames[i], ')'))) # remove the original object from memory
  6. ## do some processing here, such as:
  7. ## * filtering
  8. ## * despiking, etc ...
  9. d[['temperature']] <- despike(d[['temperature']])
  10. assign(varName[i], d)
  11. }

Note that I assign the named object to an object called d (my default variable name for “data”), remove the original object (only really necessary when the objects are large, such as with ADCP data, for example), perform a series of processing steps, and then assign d back to a named object (and probably save the new version).

Note that another way of doing the loop is to loop directly through the character vector, which would look like:

  1. for (name in varNames) {
  2. load(paste(name, '.rda', sep='')
  3. d <- get(name)
  4. eval(parse(text=paste('rm(', name, ')')))
  5. d[['temperature']] <- despike(d[['temperature']])
  6. assign(name, d)
  7. }

I like the elegance of looping through names, though I often default to the “index” loop for technical reasons (such as filling a matrix with the temperature time series from each microCAT).

发表评论

表情:
评论列表 (有 0 条评论,293人围观)

还没有评论,来说两句吧...

相关阅读