1

I'd like a readline() function to use the strings stored to a variable rather than convert the word used for the variable into the string. Is there a way I can do this?

For example, say I have the following variables and desired prompt:

> SpringC = c("Red", "Orange", "Yellow", "Green")
> WinterC = c("Blue", "White", "Purple", "Grey")
> x <- readline("Enter Season Color: ")

From this I'd like it if this would happen is:

Enter Season Color: WinterC
> x <- as.character(unlist(strsplit(x, ",")))

> x
"Blue" "White" "Purple" "Grey"

Rather than what actually happens:

Enter Season Color: WinterC
> x <- as.character(unlist(strsplit(x, ",")))

> x
"WinterC"
albeit2
  • 83
  • 7

2 Answers2

1

This would be easier if you stored your related values in a list rather than separate varaibles

options <- list(
    SpringC = c("Red", "Orange", "Yellow", "Green"), 
    WinterC = c("Blue", "White", "Purple", "Grey")
)
x <- readline("Enter Season Color: ")
x <- options[[x]]

Otherwise you can use get() with the string value of the name of a variable to retrieve it but I strongly recommend the former solution.

MrFlick
  • 195,160
  • 17
  • 277
  • 295
  • When I try this method it still doesn't come out with the colors, it comes out with "options[[1]]" or "x <- options[[1]]" – albeit2 Feb 02 '17 at 16:38
  • This works if it's sourced as one block else you need to put your reply after the readline lines like `x <- readline("Enter Season Color: ") WinterC options <- list( SpringC = c("Red", "Orange", "Yellow", "Green"), WinterC = c("Blue", "White", "Purple", "Grey") ) as.character(options[[x]])` – Zaide Chris Nov 05 '20 at 00:28
0

That is something you can do with a user defined function. Something like this:

#define the function
readline_2 <- function() {

  x <- readline("Enter Season Color: ")
  eval(parse(text = x))

}

Use:

> b <- readline_2()
Enter Season Color: WinterC
> b
[1] "Blue"   "White"  "Purple" "Grey"  
LyzandeR
  • 37,047
  • 12
  • 77
  • 87
  • Great!! Thank you so much! – albeit2 Feb 02 '17 at 16:39
  • You are very welcome, happy to help :). For simple problems like the one you describe `eval(parse...` will work fine, but for more complicated ones I think MrFlicks idea is better because it does not rely on text parsing (which is what `eval(parse...` is). – LyzandeR Feb 02 '17 at 16:47