Sam Gilbert
Sam Gilbert

Reputation: 1702

How to resolve a character string as a variable

I would like to loop through each of the below variables and print the name of the variable (for example "variable1") but also print the variable value (for example 5) in the log. Any help would be appreciated, thanks

variable1 <- 5
variable2 <- 3
variable3 <- 1

variable_list <- c("variable1", "variable2", "variable3")

for (i in variable_list) {
  print(i)
}

Upvotes: 0

Views: 183

Answers (2)

akrun
akrun

Reputation: 886938

You could also do:

 for(i in variable_list){
   cat(paste0("\t", sprintf("%s %d \n", i, get(i))))
 }

returns:

 variable1 5 
 variable2 3 
 variable3 1 

Upvotes: 1

phonixor
phonixor

Reputation: 1693

i prefer the other guys answer, but more general you can execute strings of R code by using a combination of eval and parse

variable1 <- 5
variable2 <- 3
variable3 <- 1

variable_list <- c("variable1", "variable2", "variable3")

for (i in variable_list) {
  print(i)
  print(eval(parse(text=i)))
}

returns:

[1] "variable1"
[1] 5
[1] "variable2"
[1] 3
[1] "variable3"
[1] 1

Upvotes: 1

Related Questions