Reputation: 95
I try to assign values to nested s4 classes slots in R in a dynamic way. What I have so far is the code below. I create the following nested classes ending with nested slot of type numeric.
setClass('slot', slots = c(slot = 'numeric'))
setClass('object', slots = c(slot = 'slot'))
object = new('object')
object@slot@slot
Typical assignement works as expected:
object@slot@slot = 1
or:
slot(object@slot, "slot") <- 1
What I want do to however is a dynamic creation of the slot names for the assignment for example with paste from a vector like e.g.
slot_path = c("object", "slot", "slot")
Using eval and parse does the trick to convert the string into the object and shows me the object or in that case here the slot of the object.
eval(parse(text = paste(slot_path, collapse="@")))
However assigning values to that kind of construct seems not to work as expected.
eval(parse(text = paste(slot_path, collapse="@"))) <- 2
Gives me the error that says:
Error in file(filename, "r") : cannot open the connection.
If I paste the path manually like that:
eval(parse(text = "object@slot@slot")) <- 1
I get the error that says:
Error in eval(parse(text = "object@slot@slot")) <- 1 : target of assignment expands to non-language object
Trying to assign with the assign()
function also does not do the trick.
The call below:
assign(x = slot(eval(parse(text = "object@slot")), "slot"), value = 1)
Gives me the error:
Error in assign(x = slot(eval(parse(text = "object@slot")), "slot"), value = 1) : invalid first argument
Any help with that would be appreciated.
Upvotes: 3
Views: 1158
Reputation: 95
I found a solution:
For numeric:
eval(parse(text = eval(expression(paste(pasted_slot_path, "<-", value)))))
For character:
value = sprintf('"%s"',value)
eval(parse(text = eval(expression(paste(pasted_slot_path, "<-", value)))))
Upvotes: 1