Show an object/variable with different names in R?

Asked

Viewed 1,104 times

4

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
}
  • 1

    As stated in the answer, this is possible, but it’s a bad idea. It would be much better to save the value in a vector with names, a list, or some other object.

  • I will consider your idea in my next routines. Thanks @Molx!

2 answers

4

You can also use the function get:

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

2


You can replace your last line by the following:

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

The function parse transforms the string that is the contents of the variable nomevar in 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 use is not very common or recommended. There must be better ways to get the same result probably using lists or Nvironments.


See how I would loop your loop 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]])
}
  • Thanks @Daniel. I don’t know if this is the best way or the easiest, I applied this reasoning in two moments. First, in an intermediate step of a routine, where I need to see the results!

  • 1

    See what I added in the reply! I know the way it works, but I believe that using lists is easier to program!!

  • @Danielfalbel It would be better to use a pre-populated list, or a lapply, instead of growing the list results. This can be quite problematic if the list is large. (See The R Inferno Circle 2)

  • 1

    @Molx of course! Here it was just to keep the same structure as Jean’s loop

  • @Molx understood. In this specific case I managed to solve problem. But I’m already printing The R Inferno Circle 2 to read weekend. Thanks

Browser other questions tagged

You are not signed in. Login or sign up in order to post.