R: Working with named objects in a loop

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:

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:

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

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:

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

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).

Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s