R 为什么我的sappy函数要构建一个整数向量?

R 为什么我的sappy函数要构建一个整数向量?,r,vector,sapply,R,Vector,Sapply,我有两个相关的问题——我正在努力正确地学习R,所以我正在做一些R课程的家庭作业。他们让我们写一个函数来返回相关向量: example.function <- function(threshold = 0) { example.vector <- vector() example.vector <- sapply(1:30, function(i) { complete.record.count <- # ... counts the complete re

我有两个相关的问题——我正在努力正确地学习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)
}
我不明白为什么
sapply
会把整数推到向量中?我错过了什么

我实际上不了解核心结构,或多或少:

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

some.vector如果您使用
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
}

example.function很好地解决了代码和所有问题,但我缺少
complete.record.count
。您知道
str()
函数吗?希望您能解释投票结束的原因。我不是唯一一个能够打印值但不能将其添加到向量的人。我认为您的问题在于您使用的是
示例.vector
,它既可以作为
sapply
输出,也可以作为应用函数内的全局变量。阅读
sapply
的文档和示例:它不是要这样工作的。我投票决定结束,因为我发现您的问题过于本地化,即不太可能以当前的格式帮助任何未来的访问者。另外,如果你没有一个冗长且不可重复的例子,而是试图将问题分解为一些小问题,那么你可能已经发现自己做错了什么。是的,最后一部分很糟糕,应该是
some.vector这很有帮助。我将重做这个例子,使它实际上是可复制的。
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
}