【问题标题】:Having a readline() use the strings saved to a variable in its prompt - R让 readline() 在其提示符中使用保存到变量中的字符串 - R
【发布时间】:2017-02-02 16:20:57
【问题描述】:

我想要一个 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"

【问题讨论】:

    标签: r string variables command-prompt readline


    【解决方案1】:

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

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

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

    【讨论】:

    • 当我尝试这个方法时它仍然没有出现颜色,它出现了 "options[[1]]" 或 "x
    • 如果它的来源是一个块,则此方法有效,否则您需要将您的回复放在阅读行之后,如x &lt;- readline("Enter Season Color: ") WinterC options &lt;- list( SpringC = c("Red", "Orange", "Yellow", "Green"), WinterC = c("Blue", "White", "Purple", "Grey") ) as.character(options[[x]])
    【解决方案2】:

    这是你可以用用户定义的函数来做的事情。像这样的:

    #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"  
    

    【讨论】:

    • 太棒了!!非常感谢!
    • 不客气,乐于助人:)。对于像你描述的eval(parse... 这样的简单问题,我认为更复杂的问题更好,因为它不依赖文本解析(eval(parse... 就是这样)。
    猜你喜欢
    • 1970-01-01
    • 2011-03-16
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-07-17
    • 1970-01-01
    • 2019-12-17
    • 2021-12-23
    相关资源
    最近更新 更多