【问题标题】:Why is my sapply function building a vector of integers?为什么我的 sapply 函数要构建一个整数向量?
【发布时间】: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 &lt;- sapply(range, function(i) {[...]; return(new.value)}。不要在其他任何地方使用some.vector,尤其是在要应用的函数体内。

标签: r vector sapply


【解决方案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 是如何影响匿名函数的,并且该问题不可重现...

【讨论】:

  • 这很有帮助。我将重新编写示例,使其实际上是可重现的。
猜你喜欢
  • 1970-01-01
  • 2014-05-22
  • 2013-09-18
  • 2019-12-05
  • 2023-04-09
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2017-12-23
相关资源
最近更新 更多