如何选择功能的输入选项

时间:2017-12-13 09:35:30

标签: r function

我正在尝试编写一个充当自动更正的函数。所以基本上在脚本的某个地方,用户会为变量分配颜色,然后函数检查它是否是该颜色的常见拼写错误列表的一部分,然后分配正确的拼写。

Player audioPlayer = Manager.createRealizedPlayer(url);
audioPlayer.start();

然后用户会指定一种颜色:

autocorrect = function(variable = variable) {
if (variable %in% c("grren",
                  "geen",
                  "freen",
                  "grees",
                  "grean",
                  "geren",
                  "gren",
                  "breen",
                  "gree",
                  "greeny",
                  "genn",
                  "greeen",
                  "grenn",
                  "greena",
                  "dreen",
                  "greent",
                  "greeg",
                  "greetn",
                  "greem",
                  "tgreen",
                  "greenly",
                  "agreen",
                  "grene",
                  "treen",
                  "greean",
                  "greesn",
                  "3green",
                  "reen",
                  "greeno",
                  "greeb",
                  "grrens")) {

variable <- "green"
  }
}

拼写错误。然后,该函数将颜色重新分配给正确的拼写:

colour <- "grene"

如何让函数使用各种变量名作为输入?例如,如果我有:

colour
"green"

然后使用它:

colour1 <- "grene"
colour2 <- "grean"

任何帮助将不胜感激。

1 个答案:

答案 0 :(得分:0)

您需要在函数中添加return值,以返回校正后的颜色,或者,如果颜色不匹配,则返回其他一些返回值。该参数也应该被称为比variable更有意义的东西,例如str(对于字符串)。这是一个修订过的功能:

autocorrect = function(str) {
  if (str %in% c("grren",
                      "geen",
                      "freen",
                      "grees",
                      "grean",
                      "geren",
                      "gren",
                      "breen",
                      "gree",
                      "greeny",
                      "genn",
                      "greeen",
                      "grenn",
                      "greena",
                      "dreen",
                      "greent",
                      "greeg",
                      "greetn",
                      "greem",
                      "tgreen",
                      "greenly",
                      "agreen",
                      "grene",
                      "treen",
                      "greean",
                      "greesn",
                      "3green",
                      "reen",
                      "greeno",
                      "greeb",
                      "grrens")) {

    return("green")
  } else {
    return(str)
  }
}

这会将字符串作为参数并返回更正的值,如果在自动更正列表中找不到,则返回原始字符串。如果不匹配,您还可以考虑返回NA或类似内容。

一些示例输出:

> autocorrect("grene")
[1] "green"
> autocorrect("banana")
[1] "banana"
> colour1 <- "grene"
> colour2 <- "grean"
> autocorrect(colour1)
[1] "green"
> autocorrect(colour2)
[1] "green"
>