简体   繁体   中英

How to assign a variable values stored in a vector to a series of variable names stored in a character vector in R?

I am trying to determine how to assign variable a values stored in a vector to a series of variable names stored in a character vector in R?

Here is a toy example of what I'm trying to do: I would like to have ultimately have the values 1, 2, and 3, stored in the variables A, B, and C respectively, so that print(A) returns 1 , print(B ) returns 2 , etc. However, I would like to store the variables A, B, and C as character values in a vector called my_variables . So:

my_variables <-c("A", "B", "C")

and I have the values 1, 2, 3, stored in a vector called my_values:

my_values <-1:3

I tried to use this, but it didn't quite work the way I wanted:

   assign(my_variables, my_values)

This simply assigns "A" "B" "C" to the variable my_variables, but nothing is assigned to the variable A .

I can accomplish what I want to do with an array, but I wonder if there is a more efficient way to do this with vectorized operations? Is there a better way to approach this than using a loop?

assign is not vectorized, so you can use Map here specifying the environment.

Map(function(x, y) assign(x, y, envir = .GlobalEnv), my_variables, my_values)

A
#[1] 1
B
#[1] 2
C
#[1] 3

However, it is not a good practice to have such variables in the global environment.

Use a named vector :

name_vec <- setNames(my_values, my_variables)
name_vec
#A B C 
#1 2 3 

Or named list as.list(name_vec) .

This will do the trick

val = 1:3
var = LETTERS[1:3]

l = as.list(val)
names(l) = var
list2env(l, envir = environment())

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM