在 R 中使用 readline 函数分配变量?

Assigning a variable using readline function in R?

虽然这应该很简单,但我在使用 readline 函数分配变量时遇到了问题。

fun <- function(x){
x <- readline(prompt="Please choose your color 'red, blue, yellow' ")
 if (x=="red") {
   x<-1}
 else if (x=="blue") {
   x<-2}
 else if (x=="yellow") {
   x<-3}
 else {print("Please choose the color provided above")}
return(x)
}

对我来说,这个简单的代码应该绝对有效。尽管看起来工作正常,但代码并未将新变量(1、2 或 3)分配给 x。当我 运行 代码时,它会 return x 的新值,但不会存储新的 x 值。如果我的代码有任何错误,你能帮我吗?非常感谢。

你没有展示你是如何使用这个函数的,但我猜你想这样称呼它:

foo(x)

但是你应该做的是这样称呼它:

x = foo()

(并且 x 不需要预先存在:您不是在覆盖现有变量,而是在创建一个新变量。)

事实上,函数的 参数 x 是不必要的(你没有使用它)。此外,您的功能可以大大简化:

fun = function() {
    x = readline(prompt="Please choose your color 'red, blue, yellow' ")
    switch(x, red = 1, blue = 2, yellow = 3,
           stop('Please choose a color provided above'))
}