[R] assigning the class of an object

William Dunlap wdunlap at tibco.com
Tue Sep 10 23:41:17 CEST 2013


You could use assign(name, newValue, envir=env) but I prefer env[[name]]<-newValue
since the env[[name]] works on either side of the assignment operator.  E.g.,

> env <- new.env() # or environment() if you prefer to put things in the current environment
> objNames <- load("Robject.RData", envir=env) # contains zzz<-17 and xxx<-23:24
> sapply(objNames, function(objName)class(env[[objName]]) <- "someClass")
        zzz         xxx
"someClass" "someClass"
> env$xxx
[1] 23 24
attr(,"class")
[1] "someClass"
> env$zzz
[1] 17
attr(,"class")
[1] "someClass"

Bill Dunlap
Spotfire, TIBCO Software
wdunlap tibco.com


> -----Original Message-----
> From: r-help-bounces at r-project.org [mailto:r-help-bounces at r-project.org] On Behalf
> Of Davis, Brian
> Sent: Tuesday, September 10, 2013 12:55 PM
> To: r-help at r-project.org
> Subject: [R] assigning the class of an object
> 
> I'm sure this has been answered before but alas my googlefoo is not that strong.
> 
> I have several .Rdata files with a single object in them.  I need to set the class of the
> object to "myClass".  Unfortunately, I don't know the name of the object beforehand.
> Obviously I could ls() and get the name but as I have quite a few of these I'd like to do it
> programmatically.
> 
> 
> I thought something like this would work, but I get an error.
> 
> >obj_name <- load("Robject.RData")   # get the name of the loaded object
> >class(get(obj_name)) <- "myClass"
> 
> Error in class(get(obj_name)) <- " myClass " :
>   could not find function "get<-"
> 
> 
> So I guess the question is how do I set the class of an R object when I only have the
> object name as a character string?
> 
> Thanks in advance,
> 
> Brian
> 
> ______________________________________________
> R-help at r-project.org mailing list
> https://stat.ethz.ch/mailman/listinfo/r-help
> PLEASE do read the posting guide http://www.R-project.org/posting-guide.html
> and provide commented, minimal, self-contained, reproducible code.



More information about the R-help mailing list