On 09/11/13 09:16, peter dalgaard wrote:
On Sep 10, 2013, at 22:56 , Rolf Turner wrote:

On 09/11/13 07:54, Davis, Brian wrote:
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?
(a) Actually, a wee experiment that I did indicates that your strategy actually 
*works* despite the error message!!!
That is, you wind up with an object, named by obj_name, with class "myClass". I 
don't understand this.  Perhaps
someone more knowledgeable than I will enlighten us both.
It certainly won't work universally:

x <- 5
obj_name <- "x"
class(get(obj_name))<-"foo"
Error in class(get(obj_name)) <- "foo" : could not find function "get<-"
x
[1] 5

so further details of your wee experiments need to be revealed.

Hmmm.  I did:

x <- 42
save(x,file="Robject.RData")
rm(list=ls())
obj_name <- load("Robject.RData")
class(get(obj_name)) <- "myClass"
x

and got:

[1] 42
attr(,"class")
[1] "myClass"

(also got the familiar error message).

When I did it your way --- without the saving and loading bit --- I got
the same result that you did.  I.e. assigning the class that way did *not*
work (as one would expect it wouldn't!).

This is weird, n'est-ce pas?

Here is my

> sessionInfo()
R version 3.0.1 (2013-05-16)
Platform: x86_64-unknown-linux-gnu (64-bit)

locale:
[1] C

attached base packages:
[1] stats     graphics  grDevices utils     datasets  methods base

other attached packages:
[1] misc_0.0-15

    cheers,

    Rolf

______________________________________________
R-help@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.

Reply via email to