I have a list mylist
which gets populated in a recursive function -- however, when accessing the elements later within the recursion, they are still NULL.
A minimal example:
mylist = vector("list",5)
myf = function(x){
if(x==1){
mylist[[x]] = "hi"
message("Set value at position ",x," to ",mylist[[x]])
force(mylist[[x]] = "hi")
}
else{
mylist[[x]] = "hi"
message("Set value at position ",x," to ",mylist[[x]])
myf(x-1)
message("Value at position ",x-1, " is ",mylist[[x-1]])
}
}
Which yields
Set value at position 4 to hi
Set value at position 3 to hi
Set value at position 2 to hi
Set value at position 1 to hi
Value at position 1 is
Value at position 2 is
Value at position 3 is
You can see that I tried force(...) but without success.
On the discussion of global vs local variable, it has been suggested here to use <<-
instead of the =
assignment symbol to set the global variable. However, this does not help here. It has been further recommended in answers to that post to use assign(...)
but it looks to me as if that would not work for lists.