R: Working with named objects in a loop
2017-07-19 15:26
337 查看
R: Working with named objects in a loop
Leavea 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
dback
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).
相关文章推荐
- Working with Configuration Files (app.config) in C++/CLI
- Working with collections in WCF RIA Services (part 2)
- Working with Configuration Files (app.config) in C++/CLI
- Working with the TextBox Control In Silverlight 4.0
- Working with Managed Paths in MOSS
- 第一篇译作:Working With Unicode in C++(在c++中使用Unicode)
- In-App Purchase Programming Guide----(六) ----Working with Subscriptions
- Working with windows in chrome code
- READING NOTE: Inside-Outside Net: Detecting Objects in Context with Skip Pooling and Recurrent Neura
- There is no getter for property named 'column' in 'class java.lang.String'] with root cause
- Working with UITableView in Xcode 5 Using Storyboard
- Working with binary large objects (BLOBs)
- Working with DbGeography, Points and Polygons in .NET
- Working with tempdb in SQL Server 2005
- #3 working with data stored in files && securing your application
- Working with JSON in iOS 5 Tutorial
- Working with large lists in MOSS2007(四)
- Problem with Anonymous delegate in loop
- Xslt语法中使用.NET对象(Xslt Working with Extension Objects)
- Working with EXIT, STOP, CONTINUE and RETURN in SAP ABAP