2013-10-04 40 views
4

我已经writen这个功能与几个测试案例:功能让我总是尾随`NULL`回

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))

UPDATE

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))) 
    } 
} 

回答

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声明,以避免不返回输出并不是那么好。

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()函数,并且当您在顶层评估函数时,不会打印这些值。例如。

f4 <- function() { 
    cat("hello, world!\n") 
    invisible(1) 
} 

将返回1(如可以通过指定它的返回值,一些变量检查),但是从顶层调用时不会打印1。事实证明,cat不可见地返回它的值(它总是NULL),因此f3的返回值也是不可见的。