Search code examples
rfunctionobjectdata-structuresr-s4

In R, how can I append new information to S4 objects from a function?


I am passing a string that represents a variable name to a function. Essentially I want to add new information to the variable, the problem I'm having is that it doesn't actually attach the new information to the S4 object, it just creates a new variable with myObjName.newinfo that is actually unrelated to the original object.

Here is what I've tried so far.

myS4 <- makeSomeS4()


myFunction <- function(myS4name)
{
    #Get the actual s4 object based on the variable name.
    res <- get(myS4name)

    #Make sure they're passing us the correct type of object.
    try(if(typeof(res) != "S4") stop("Error: extract_res_data requires S4 type object as result set for parameter res."))

    #I've tried this way with eval.
    myNum = 5
    myNum_assign <- paste(myS4name, ".myNum", " <<- ", myNum, sep="")
    eval(parse(text=myNum_assign))

    #I've tried this way with assign.
    myNum = 5
    myNum_assign = paste(resName, ".myNum", sep="")
    assign(myNum_assign, myNum, envir = .GlobalEnv)

}

So now I can run this function, then say

> myFunction("myS4")
> myS4.myNum
    5

Looks fine at first glance, but actually the myS4.myNum is it's own variable and has nothing to do with myS4. So if I later pass myS4 to another function, and then try to access .myNum, it doesn't exist.

How can I properly attach the new values to the S4? It will not always be simple data sets, sometimes I will need to attach data frames or lists for instance.

I appreciate any help anyone can offer.


Solution

  • In short, dot notation does not work like this in R. In R dots are completely valid parts of a variable name and function just like an underscore. When you assign a value to myS4.myNum you are simply creating a new variable with that name, as you discovered.

    Here's a short example of how S4 slots are used:

    setClass("my_class", representation(my_val = "numeric"))
    my_object <- new("my_class")
    my_object@my_val <- 5
    

    But there's much more to it, beyond the scope of an SO answer. Check out http://adv-r.had.co.nz/S4.html, etc., for more info on how S4 objects work.