[R] assigning the class of an object
Rolf Turner
rolf.turner at xtra.co.nz
Tue Sep 10 22:56:07 CEST 2013
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.
(b) To accomplish your task without getting an off-putting error
message, you proceed in two (three?) steps:
obj_name <- load("Robject.RData")
tempObj <- get(obj_name)
class(tempObj) <- "myClass"
assign(obj_name,tempObj)
HTH
cheers,
Rolf Turner
More information about the R-help
mailing list