0

我有两个相关的问题——我正在尝试正确地学习 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。提示?

4

1 回答 1

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影响匿名函数的,而且这个问题是不可重现的......

于 2013-01-19T20:42:28.047 回答