Intellipaat Back

Explore Courses Blog Tutorials Interview Questions
0 votes
2 views
in R Programming by (50.2k points)

I want to have the values 1, 2, and 3, stored in the variables A, B, and C respectively, so that if I write print(A), it should return 1, print(B) returns 2, etc. I want to have the variables A, B, and C as character values in a vector called my_variables . So for achieving that I have implemented the following:

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 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?

1 Answer

0 votes
by (107k points)

Basically the assign function in R programming is not vectorized, so instead of using assign() 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

But I would like to inform you that it is not a good practice to have such variables in the global environment. So now in that case you can 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).

31k questions

32.8k answers

501 comments

693 users

Browse Categories

...