2013-01-19 25 views
0

我有兩個相關的問題 - 我試圖正確地學習R,所以我正在從R課程做一些家庭作業問題。他們讓我們寫一個函數來返回一個相關矢量:爲什麼我的sapply函數會構建一個整數向量?

example.function <- function(threshold = 0) { 
    example.vector <- vector() 
    example.vector <- sapply(1:30, function(i) { 
    complete.record.count <- # ... counts the complete records in each of the 30 files. 
    ## Cutting for space and to avoid giving away answers. 
    ## a few lines get the complete records in each 
    ## file and count them. 
    if(complete.record.count > threshold) { 
     new.correlation <- cor(complete.record$val1, complete.record$val2) 
     print(new.correlation) 
     example.vector <- c(new.correlation, example.vector) 
    } 
    }) 
    # more null value handling# 
    return(example.vector) 
} 

當函數運行時,它將相關值打印到標準輸出。它打印的值精確到小數點後六位。所以我知道我獲得了很好的價值new.correlation.返回的向量不包含這些值。相反,它是整個數字的順序。

> tmp <- example.function() 
> head(tmp) 
[1] 2 3 4 5 6 7 

我想不通爲什麼sapply是推整數到載體?我在這裏錯過了什麼?

我其實不明白的核心結構,這是或多或少:

some.vector <- vector() 
some.vector <- sapply(range, function(i) { 
    some.vector <- c(new.value,some.vector) 
} 

,似乎非常UN-R-像它的冗餘。提示?

+0

與代碼和所有有趣的問題,但我缺少'complete.record.count'。你知道'str()'函數嗎? –

+0

會喜歡關閉投票的解釋。我不能成爲唯一能夠打印值但不將其添加到矢量中的人。 – Amanda

+0

我認爲你的問題是,你正在使用'example.vector'作爲你的'sapply'輸出,並且作爲應用函數的全局變量。閱讀文檔「sapply」和示例:它並不意味着以這種方式工作。我投票結束了,因爲我發現你的問題太本地化了,也就是說,不太可能幫助未來的訪問者以目前的格式。此外,如果您試圖將問題分解爲一些小問題,而不是冗長且不可重複的例子,那麼您可能會發現自己在做錯問題。 – flodel

回答

1

如果您使用sapply,您不需要自己創建載體,也不需要增加載體(sapply負責所有這些)。你可能想是這樣的:

example.function <- function(threshold = 0) { 
    example.vector <- sapply(1:30, function(i) { 
    ## Cutting for space and to avoid giving away answers. 
    ## a few lines get the complete records in each 
    ## file and count them. 
    if(complete.record.count > threshold) { 
     new.correlation <- cor(complete.record$val1, complete.record$val2) 
     } else { 
     new.correlation <- NA 
     } 
    new.correlation #return value of anonymous function 
    }) 
    # more null value handling# 
    example.vector #return value of example.function 
} 

但是,目前還不清楚該指數i因素匿名函數,問題是如何不可再生...

+0

這是有幫助的。我會重新修改這個例子,以便它可以重現。 – Amanda

相關問題