Cheng
Cheng

Reputation: 193

how can I use the object of a variable to represent a variable

for example,

name <- c("CHLYT1","CHLYT2")

assign(name[1], 2)
assign(name[2], 4)

result <- name[1]

I want the result to be 2 ,not the CHLYT1

Upvotes: 0

Views: 44

Answers (1)

Dominic Comtois
Dominic Comtois

Reputation: 10411

You could achieve this by using

result <- get(name[1])

But it's very unconventional and a recipe for a lot of confusion.


There are several approaches to deal with this kind of situations. A super simple one would be to use a simple vector with named elements:

values <- c(CHLYT1 = 2, CHLYT2 = 4)

Then you can access those values with, obviously, their name:

result <- values["CHLYT1"]

or by their position

result <- values[1]

or even by the position of their name (corresponding to your approach)

result <- values[names(values)[1]]

In all situations, result will be equal to 2.

Upvotes: 1

Related Questions