Home > Software engineering >  How do I get strings of assigned objects?
How do I get strings of assigned objects?

Time:03-01

I want to be able to get the string of the assigned values

x <- 5
y <- 'something'
models  <- c(x, y)

for (model in models){
print(model)
}

The expected results should print 'x' and 'y', while this way I am getting obviously 5 and 'something'

How should I modify my code?

Thanks

CodePudding user response:

Once you have created the vector models, R has no way to tell it was created from x and y, so you cannot recover these variable names from models unless you create models with this intention in mind. For example:

x <- 5
y <- 'something'
models  <- c(quote(x), quote(y))

for(model in models){
  print(model)
}
#> x
#> y

Or even better:

for (model in models){
  cat(model, ":", eval(model), "\n")
#> x : 5
#> y : something

An alternative might be to create a function which generates a list where both the variable name and its value are preserved:

named_list <- function(...) setNames(list(...), 
                                     sapply(as.list(match.call())[-1], deparse))

named_list(x, y)
#> $x
#> [1] 5
#>
#> $y
#> [1] "something"

CodePudding user response:

An easier way would be to use a list.

models <- list(x = 5,y = "something")

for (model in names(models)){
  print(model)
}
  •  Tags:  
  • r
  • Related