写一个R函数,它将两个单词作为参数/输入

时间:2015-06-18 18:50:59

标签: r function functional-programming

我想写一个R函数,它接受两个单词作为参数/输入,如果两个单词中的字符数相等则返回“Equal Length”,否则返回“Not Equal Length”。假设函数的名称是比较的。我希望它能够如下工作

compare("EPS568","Summer")
Equal Length
compare("EPS568","SummerA")
Not Equal Length

我已经开始了 -

compares <- function(A,B) {
if (str_length(A) == str_length(B))
return("Equal Length")
}

我正在学习R,任何帮助都会受到赞赏

4 个答案:

答案 0 :(得分:3)

你实际上需要考虑你所说的“等长”是什么意思是你在内存,计算字符或屏幕宽度?幸运的是,同样的功能处理所有三个,你只需要改变一个参数!!

compares <- function(A,B) {
# use type="chars" for the number of human readible characters
# use type="bytes" for the storage size of the characters
# use type="width" for the size of the string in monospace font
if (nchar(A, type="chars") == nchar(B,type="chars")) {
    return("Equal Length")
} else {
    return ("Not Equal Length")
}}


> A="this string"
> B="that string"
> compares(A,B)
[1] "Equal Length"
> B="thatt string"
> compares(A,B)
[1] "Not Equal Length"

答案 1 :(得分:0)

你很亲密。使用nchar代替str_length。请参阅?nchar

答案 2 :(得分:0)

我想你错过了其他分支。 如果是这种情况,请查看:

http://www.dummies.com/how-to/content/how-to-use-if133else-statements-in-r.html

这是真正的初学者,但它是一个起点;)

答案 3 :(得分:0)

如果字符串长度 相等,你已经给出了应该发生什么的说明,现在你需要说明应该发生什么:

compares <- function(A,B) {
  if (str_length(A) == str_length(B)) {
    return("Equal Length")
  }
  return("Not Equal Length")
}

您可以将else放在与if语句的结束括号(})相同的行上,但是一旦函数到达第一个return,函数就会停止运行代码,所以这里没有必要。