让 readline() 在其提示符中使用保存到变量的字符串 - R

Having a readline() use the strings saved to a variable in its prompt - R

我想要一个 readline() 函数来使用存储到变量的字符串,而不是将用于变量的单词转换为字符串。我有办法做到这一点吗?

例如,假设我有以下变量和所需的提示:

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

如果发生这种情况,我希望它是:

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

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

而不是实际发生的事情:

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

> x
"WinterC"

这是您可以使用用户定义的函数来完成的事情。像这样:

#define the function
readline_2 <- function() {

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

}

使用:

> b <- readline_2()
Enter Season Color: WinterC
> b
[1] "Blue"   "White"  "Purple" "Grey"  

如果您将相关值存储在列表中而不是单独的变量中,这会更容易

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

否则,您可以使用 get() 和变量名称的字符串值来检索它,但我强烈推荐前一种解决方案。