Search code examples
rassign

assigning value to an object when referencing it by a string within a for loop


I often struggle with understanding how to assign values in R within loops. The desired behavior seems simple to me, but I clearly don't have a good grasp on the subtleties of evaluation and assignment in R.

For example, I've got a bunch of data objects that I want to add a comment to each object (they are unrelated and so using them together in a list beyond this assignment does not make sense). Here's a MWE


my_comment <- paste0("these objects were created on ", date())

obj1 <- "content1"
obj2 <- "content2"

obj_l <- list(obj1, obj2)

for(obj in obj_l) {
comment(obj) <- my_comment
}

## get 'NULL', but want "these objects were created ..."
comment(obj1)

## get 'NULL'
comment(obj_l)

## assignment is only made to temp variable 'obj'
## This makes sense, but not the desired outcome. 
comment(obj)

I imagine the solution will look something like the following pseudo code

obj_l <- c("obj1", "obj2")

for(name in obj_l)
 unknown_function(name, comment, my_comment, unknown_args)

}

or


modify(obj_l, my_comment, unknown_syntax)

If my pseudo code is on track, can someone help me with the unknown_ parts?


Solution

  • After some more reading of help pages and trial and error, here's my solution

    obj1 <- "content1"
    obj2 <- "content2"
    
    obj_l <- c("obj1", "obj2")
    
    comment <- '"my comment!"'
    
    for(x in obj_l) {
        my_exp <- paste0("comment(", x, ") <- ", comment)
        parse(text = my_exp)
    }
    
    comment(obj1)
    # [1] "my comment"