Search code examples
rloopsassign

R Code: how to use function 'assign' inside a loop to set attributes to n number of objects


I having issues to set attributes to n number of objects obtained from a list, trying something like this results in an error:

N=3 #or whatever number I have in the list of interest.

for (i in 1:N){

assign(paste0("obj",i),unlist(list[i],recursive=F,use.names=T))     #works great

attr(paste0("obj",i),'ID') <-'name'                                 #this is the issue 

}

gives me an error "target of assignment expands to non-language object"

I tried to solved this by using something like this:

tmp<-paste0("obj",i)
parse(file="", text=tmp)$'ID'<-'name'

and multiple variations without success. I even tried the function 'setattr' from the package 'Bit'. Does anyone knows how I can solve this?


Solution

  • Just assign the attribute first:

    mylist <- list(1:3, letters, rnorm(5))
    
    for (i in seq_along(mylist))
    {
      new_object <- unlist(mylist[i], recursive = FALSE, use.names = TRUE)
      attr(new_object, "ID") <- "name"
      assign(paste0("obj", i), new_object)
    }
    
    obj1
    #> [1] 1 2 3
    #> attr(,"ID")
    #> [1] "name"
    obj2
    #>  [1] "a" "b" "c" "d" "e" "f" "g" "h" "i" "j" "k" "l" "m" "n" "o" "p" "q" "r" "s"
    #> [20] "t" "u" "v" "w" "x" "y" "z"
    #> attr(,"ID")
    #> [1] "name"
    obj3
    #> [1] -1.296529567  0.932548362 -0.935856164  0.002168237  0.024290270
    #> attr(,"ID")
    #> [1] "name"