打印功能对sapply的影响是什么?

时间:2014-05-01 15:31:48

标签: r

data <-c("001","002","103","119","129")
n1<- sapply(data,function(x){
    x<-gsub(pattern="(\\d+)(\\d\\d)$","\\2",x)
    if(gsub("(\\d)(\\d)","\\1",x)=="0")
         x <- gsub("(\\d)(\\d)","\\2",x)
     },USE.NAMES=FALSE)

n2<- sapply(data,function(x){
    x<-gsub(pattern="(\\d+)(\\d\\d)$","\\2",x)
    if(gsub("(\\d)(\\d)","\\1",x)=="0")
         x <- gsub("(\\d)(\\d)","\\2",x)
     print(x)},USE.NAMES=FALSE)

为什么n2可以得到&#34; 1&#34; &#34; 2&#34; &#34; 3&#34; &#34; 19&#34; &#34; 29&#34; ,n1不能?n2比n1更多一行print(x),打印功能在这里有什么影响?

1 个答案:

答案 0 :(得分:1)

当我们应用更好的缩进并添加一些空格时,这里发生的事情更容易发现:

n2 <- sapply(data, function(x) {
    x <- gsub(pattern = "(\\d+)(\\d\\d)$", "\\2", x)
    if (gsub("(\\d)(\\d)", "\\1", x) == "0") x <- gsub("(\\d)(\\d)", "\\2", x)
    print(x)
}, USE.NAMES=FALSE)

如果您不使用显式return语句,R将返回上一次操作的结果。在第一种情况下,当if语句失败时,将跳过最后一个x <-,并返回NULL。添加print(x)都会将数字打印到屏幕上,并使其从函数返回。这解释了第二种情况总是具有有效的(非NULL)返回值。

我会使用print(x)return(x)来代替x