我已经用几个测试用例编写了这个函数:
characterCounter <- function(char1, char2) {
if(is.null(char1) || is.null(char2)) {
print("Please check your character sequences!")
return()
}
if(nchar(char1, type = "chars") < nchar(char2, type = "chars") || nchar(char1, type = "chars") <= nchar(char2, type = "chars")) {
cat(sprintf("%s is smaller or smaller-equal than %s\n", char1 , char2))
return()
} else if(nchar(char1, type = "chars") > nchar(char2, type = "chars") || nchar(char1, type = "chars") >= nchar(char2, type = "chars")) {
cat(sprintf("%s is greater or greater-equal than %s\n", char1 , char2))
return()
} else if(nchar(char1, type = "chars") == nchar(char2, type = "chars")) {
cat(sprintf("%s is equal to %s\n", char1, char2))
return()
}
}
#Testcases
(characterCounter("Hello","Hell"))
(characterCounter("Wor","World"))
然而,在每个案例之后我都会回来:
> (characterCounter("Hello","Hell"))
Hello is greater or greater-equal than Hell
NULL
> (characterCounter("Wor","World"))
Wor is smaller or smaller-equal than World
NULL
我在输出中不喜欢的是尾随NULL
。为什么我要回来?
(characterCounter(NULL,NULL))
更新
characterCounter <- function(char1, char2) {
if(is.null(char1) || is.null(char2)) {
return(cat("Please check your character sequences!"))
}
if(nchar(char1, type = "chars") < nchar(char2, type = "chars") || nchar(char1, type = "chars") <= nchar(char2, type = "chars")) {
return(cat(sprintf("%s is smaller or smaller-equal than %s\n", char1 , char2)))
} else if(nchar(char1, type = "chars") > nchar(char2, type = "chars") || nchar(char1, type = "chars") >= nchar(char2, type = "chars")) {
return(cat(sprintf("%s is greater or greater-equal than %s\n", char1 , char2)))
} else if(nchar(char1, type = "chars") == nchar(char2, type = "chars")) {
return(cat(sprintf("%s is equal to %s\n", char1, char2)))
}
}
答案 0 :(得分:3)
你得到NULL
,因为这就是你的回报。尝试使用invisible
:
f1 = function() {
cat('smth\n')
return()
}
f2 = function() {
cat('smth\n')
return(invisible())
}
f1()
#smth
#NULL
f2()
#smth
请注意,如果强制带有额外括号的输出,您仍会获得NULL
:
(f2())
#smth
#NULL
最后,作为一般编程注释,我认为除了单行之外,非常希望在函数和解决方案中使用return
语句,以避免因返回而导致的输出不是那么好。
答案 1 :(得分:3)
R中的每个函数都会返回一些值。如果没有明确的返回值,它将是return
调用或最后一个求值语句的参数。
考虑三个功能:
f1 <- function() {
cat("Hello, world!\n")
return (NULL)
}
f2 <- function() {
cat("Hello, world!\n")
NULL
}
f3 <- function() {
cat("Hello, world!\n")
}
当你运行它们时,你得到:
> f1()
Hello, world!
NULL
> f2()
Hello, world!
NULL
> f3()
Hello, world!
然而第三个函数也会返回NULL
,因为您可以通过分配x <- f3()
和评估x
来轻松检查。为什么不同?
原因是某些函数返回其值不可见,即使用invisible()
函数,并且在评估顶级函数时不会打印这些值。 E.g。
f4 <- function() {
cat("hello, world!\n")
invisible(1)
}
将返回1(因为您可以通过将其返回值分配给某个变量来检查),但是从顶层调用时不会打印1。事实证明cat
无形地返回其值(它总是NULL
),因此f3
的返回值也是不可见的。