Nova
Nova

Reputation: 618

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?

Upvotes: 1

Views: 621

Answers (2)

akrun
akrun

Reputation: 887991

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

Upvotes: 2

Ian Campbell
Ian Campbell

Reputation: 24888

One approach is with eval(parse(text=expression)), which can often be pressed into service in an emergency. But I would try to avoid it as much as possible.

name <- "test_list"
assign(name, list(a = c(1,2), b = c(3,4)))
eval(parse(text=paste0(name,"$a[[1]] <- 5")))
test_list
$a
[1] 5 2

$b
[1] 3 4

Upvotes: 1

Related Questions