您的位置:首页 > 移动开发 > Objective-C

R: Working with named objects in a loop

2017-07-19 15:26 337 查看



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:
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).
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: