Search code examples
rassign

How to assign values to an object without directly typing out the object in R?


Let's say I create a list using the assign function:

name <- "test_list"
assign(name, list(a = c(1,2), b = c(3,4)))

Now, let's say I want to assign a new value to test_list without typing it out directly (like in a situation where I want objects with specific names to be generated automatically).

Both of the following attempts didn't work:

1.)

as.name(name)$a[[1]] <- 5

2.)

eval(expr = as.name(name))$a[[1]] <- 5

Any ideas?


Solution

  • We can use

    assign(name, `[<-`(get(name),  get(name)$a[1], 5))
    

    Or make this more explicit

    assign(name, {dat <- get(name); dat$a[1] <- 5; dat})
    

    Or extract the object from the globalenv and assign

    .GlobalEnv[[name]]$a[1] <- 5
    test_list
    #$a
    #[1] 5 2
    
    #$b
    #[1] 3 4