让readline()使用保存到变量提示符-R中的字符串
我希望readline()函数使用存储到变量的字符串,而不是将用于变量的单词转换为字符串。我有办法做到这一点吗 例如,假设我有以下变量和所需的提示:让readline()使用保存到变量提示符-R中的字符串,r,string,variables,command-prompt,readline,R,String,Variables,Command Prompt,Readline,我希望readline()函数使用存储到变量的字符串,而不是将用于变量的单词转换为字符串。我有办法做到这一点吗 例如,假设我有以下变量和所需的提示: > SpringC = c("Red", "Orange", "Yellow", "Green") > WinterC = c("Blue", "White", "Purple", "Grey") > x <- readline("Enter Season Color: ") >SpringC=c(“红色”、“橙色”、“黄
> SpringC = c("Red", "Orange", "Yellow", "Green")
> WinterC = c("Blue", "White", "Purple", "Grey")
> x <- readline("Enter Season Color: ")
>SpringC=c(“红色”、“橙色”、“黄色”、“绿色”)
>冬季c=c(“蓝色”、“白色”、“紫色”、“灰色”)
>x这是可以通过用户定义的函数来实现的。大概是这样的:
#define the function
readline_2 <- function() {
x <- readline("Enter Season Color: ")
eval(parse(text = x))
}
#定义函数
readline_2如果将相关值存储在一个列表中而不是单独的变量中,这将更容易
options <- list(
SpringC = c("Red", "Orange", "Yellow", "Green"),
WinterC = c("Blue", "White", "Purple", "Grey")
)
x <- readline("Enter Season Color: ")
x <- options[[x]]
options当我尝试这种方法时,它仍然不会显示颜色,而是显示“options[[1]]”或“如果它来源于一个块,则此功能有效,否则您需要将回复放在阅读行之后,如x Great!!非常感谢你!非常欢迎,很乐意帮助:)。对于像您描述的eval(parse…
)这样的简单问题,我认为MrFlicks的想法更好,因为它不依赖于文本解析(这就是eval(parse…
)。
#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]]