【发布时间】:2013-01-19 20:27:26
【问题描述】:
我有两个相关的问题——我正在努力正确地学习 R,所以我正在做一些 R 课程的家庭作业问题。他们让我们编写一个函数来返回相关向量:
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)
}
在冗余方面看起来非常不像 R。尖端?
【问题讨论】:
-
关于代码和所有内容的好问题,但我错过了
complete.record.count。你知道str()函数吗? -
希望对投票结束的解释。我不能是唯一能够打印值但不能将其添加到向量的人。
-
我认为您的问题是您将
example.vector用作sapply输出和正在应用的函数内的全局变量。阅读sapply的文档和示例:它并不意味着以这种方式工作。我投票结束,因为我发现您的问题过于本地化,即不太可能以当前格式帮助任何未来的访问者。此外,如果您尝试将问题分解为小问题,而不是冗长且不可重现的示例,那么您可能会自己发现自己做错了什么。 -
是的,最后一部分很糟糕,应该是
some.vector <- sapply(range, function(i) {[...]; return(new.value)}。不要在其他任何地方使用some.vector,尤其是在要应用的函数体内。