【问题标题】:Save results from a function that contains a for loop保存包含 for 循环的函数的结果
【发布时间】:2019-02-09 20:11:54
【问题描述】:

专家

我创建了一个函数来计算满足某些条件的行数。我制作这个函数是因为其中一个条件必须采用向量中的不同标签 - 我没有使用过滤器,因为我必须更改过滤器上的一个条件并一遍又一遍地返回原始数据帧. 我的功能:

counting <- function(df, na.rm = TRUE, ...) {

    for (i in seq_along(counties)) {   
      observations<-
      nrow(subset(financial_environment, 
financial_environment$county==counties[i]
                  & population> 500000))
      print(observations) }
}
counting(financial_environment)

问题是如何将控制台的输出保存在一个向量中(里面有一个 for 循环)。 我想让这个向量在我的代码中创建一个包含先前向量的数据框。

我阅读了其他 stackoverflow 问题,但与我制作的功能相比,这些功能看起来有点基本。这些答案建议如下:

创建一个将保存结果的向量。 results &lt;- vector("numeric", 650L)

那就改一行函数:

counting <- function(df, na.rm = TRUE, ...) {

    for (i in seq_along(counties)) {   
      observations<- 
      nrow(subset(financial_environment, 
financial_environment$county==counties[i]
                  & population> 500000))
      print(observations)}

接下来,我只需将函数应用于数据框并查看“结果”向量 counting(financial_environment) results 通过这样做,“结果”向量内部只有零。

我也尝试了sapply,但控制台显示了 1000 个观察值。我注意到结果是重复的,即最后 450 个输出是应用该函数时的前 450 个输出。

非常感谢您的 cmets 和建议。

【问题讨论】:

  • 我没有得到您真正尝试保存的内容,但函数的最后一个值在 R 中返回,或者您可以使用 return 函数显式返回。作为另一种选择,您可以使用 assign 函数全局分配值(但这被认为是不好的风格)
  • 我想你想在循环之前使用observations &lt;- vector("numeric", 650),然后在循环内部使用observations[i] &lt;- ...(the same)。循环后还要加上return(observations)
  • 另外,如果你真的需要一个函数,你应该重新考虑。从您的示例中,您从未在代码中使用过它的任何参数。或者,也许您想使用变量 df(argument) 而不是未在函数范围内声明的特定数据框 (financial_environment)
  • 获取一些数据会有所帮助。编辑您的帖子并添加 'dput()' 。如果输出很多,请使用 'dput(head())'。

标签: r function for-loop data-science policy


【解决方案1】:

如果我理解正确,这样的事情应该可以工作:

results <- vector("numeric", 650L)

counting <- function(someOption) {
  for (i in seq_along(someOption)) {   
    observation <- insertHereYourCodeForObservation
    results[i] <- observation
  }
  results
}

results <- counting(someOption = someData)

在这种情况下,函数返回 results 数组,然后显式分配给 results

或者,results 的值可以像这样使用&lt;&lt;- 从函数内部直接更改(正如 Ben373 所指出的,不推荐使用):

results <- vector("numeric", 650L)

counting <- function(someOption) {
  for (i in seq_along(someOption)) {   
    observation <- insertHereYourCodeForObservation
    results[i] <<- observation
  }
}

counting(someOption = someData)

请注意,在后面的代码中,函数没有返回任何内容。

【讨论】:

    猜你喜欢
    • 2018-12-09
    • 2019-02-08
    • 1970-01-01
    • 1970-01-01
    • 2021-12-24
    • 2022-01-20
    • 1970-01-01
    • 1970-01-01
    • 2021-05-04
    相关资源
    最近更新 更多