'How do I get strings of assigned objects?

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

r


Solution 1:[1]

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"

Solution 2:[2]

An easier way would be to use a list.

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

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

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1
Solution 2 Kevin Chen