编写一个R函数,该函数使用两个单词作为参数/输入
我想写一个R函数,它将两个单词作为参数/输入,如果两个单词中的字符数相等,则返回“等长”,否则返回“不等长”。假设函数名为compare。我想它的工作如下编写一个R函数,该函数使用两个单词作为参数/输入,r,function,functional-programming,R,Function,Functional Programming,我想写一个R函数,它将两个单词作为参数/输入,如果两个单词中的字符数相等,则返回“等长”,否则返回“不等长”。假设函数名为compare。我想它的工作如下 compare("EPS568","Summer") Equal Length compare("EPS568","SummerA") Not Equal Length 我从- compares <- function(A,B) { if (str_length(A) == str_length(B)) return("Equal L
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")
}
比较你很接近。使用nchar
而不是str\u length
。参见?nchar
我想你错过了else分支。
如果是这种情况,请查看:
这是为真正的初学者准备的,但这是一个起点;) 实际上,您需要思考“等长”是指内存、计数字符还是屏幕宽度?幸运的是,同一个函数处理这三个参数,您只需更改一个参数
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"
比较A=“此字符串”
>B=“该字符串”
>比较(A,B)
[1] “等长”
>B=“thatt字符串”
>比较(A,B)
[1] “长度不相等”
您已经给出了在字符串长度相等的情况下应该发生什么的说明,现在您需要说明在其他情况下应该发生什么:
compares <- function(A,B) {
if (str_length(A) == str_length(B)) {
return("Equal Length")
}
return("Not Equal Length")
}
比较好。为什么不在函数参数中添加type=“chars”
?您当然可以这样做。如果您正在学习R,这是一个简单的修改,您可以自己进行修改,并查看实现它所需的内容!将nchar
更改为str_length
,OP仍然会有相同的问题(没有其他)。为什么要切换?