Show an object / variable with different names in R?

3

Considering the following routine:

x <- 1:10

for (i in 1:length(x)) {
  ## Nome da variável:
  nomevar <- paste0("Var_", i)
  var <- x[i] + 2 
  assign(nomevar, var)
  print(nomevar) # aqui esta minha duvida
}
    
asked by anonymous 07.01.2016 / 17:47

2 answers

2

You can replace your last line with the following snippet:

print(eval(parse(text = nomevar)))

The function parse transforms the string that is the contents of the variable nomevar into an expression of R. The function eval executes the expression.

> x<-1:10
> 
> for (i in 1:length(x)){
+   ## Nome da variável:
+   nomevar<-paste0("Var_",i)
+   var<- x[i] + 2 
+   assign(nomevar,var)
+   print(eval(parse(text = nomevar)))
+ }
[1] 3
[1] 4
[1] 5
[1] 6
[1] 7
[1] 8
[1] 9
[1] 10
[1] 11
[1] 12

Note that this usage is not very common or recommended. There should be better ways to get the same result probably using lists or environments.

See how I would loop your way using more common structures in R.

x<-1:10
results <- list()
for (i in 1:length(x)){
  ## Nome da variável:
  nomevar<-paste0("Var_",i)
  results[[nomevar]]<- x[i] + 2 
  print(results[[nomevar]])
}
    
07.01.2016 / 19:02
4

You can also use the get function:

for (i in 1:length(x)) {
  ## Nome da variável:
  nomevar <- paste0("Var_", i)
  var <- x[i] + 2 
  assign(nomevar, var)
  print(get(nomevar)) 
}
[1] 3
[1] 4
[1] 5
[1] 6
[1] 7
[1] 8
[1] 9
[1] 10
[1] 11
[1] 12
    
07.01.2016 / 21:56