【问题标题】:How to add up data frames from a loop within a function?如何从函数内的循环中添加数据帧?
【发布时间】:2015-07-01 01:47:05
【问题描述】:

我有一个函数,其目的是根据成本预测收入。扭曲的是,我有许多不同的数据帧和许多不同的相应模型作为输入进行预测 - 函数循环遍历每个数据帧,在其上预测其相应的模型并输出具有置信区间的预测输出。现在,我需要找到一种方法来将所有这些预测输出相加。

这是我正在做的一个简化示例,如果您不需要它来回答问题(可能难以阅读),请随意跳过它,但如果它有助于阅读。请注意,每个预测输出都不是成本和收入的数据框,而是您可以从可变成本中获得的收入的摘要。

predictions <- function(df_list, model_list) {
  for(i in 1:length(df_list)) {
    sapply(seq(1, 2, .25), function(x) {
      df_list[[i]]$cost <- df_list[[i]]$cost * x
      predictions <- predict(model_list[[i]], df_list[[i]], interval = "confidence")
      temp <- cbind(df_list[[i]]$cost, predictions)
      output <- summarise(temp, Cost = sum(cost), Low = sum(lwr), Fit = sum(fit), Upper = sum(upr))
      output
    }) -> output
    output %>% t %>% as.data.frame -> output
  }
}

每个索引的输出如下所示:

     Cost Lower_Rev  Fit_Rev Upper_Rev
1 2048884  18114566 20898884  24145077
2 2561105  21684691 25085853  29064495
3 3073326  25092823 29122421  33853693
4 3585547  28369901 33038060  38539706
5 4097768  31537704 36853067  43140547

我需要某种方法将每个输出加在一起成为一个主输出,其成本和收入值将是所有其他输出的总和。有什么想法吗?

【问题讨论】:

    标签: r


    【解决方案1】:

    您的output 每次都会被替换。您需要将其分配给某些东西,或者只是使用lapply/sapply。还添加了i 作为参数,而不是滥用R 的范围规则并从.GlobalEnv 中获取参数i

    L = lapply(1:length(df_list),
               function(i) sapply(seq(1, 2, .25), function(x, i) {
                                  df_list[[i]]$cost <- df_list[[i]]$cost * x
                                  predictions <- predict(model_list[[i]], df_list[[i]], interval = "confidence")
                                  temp <- cbind(df_list[[i]]$cost, predictions)
                                  output <- summarise(temp, Cost = sum(cost), Low = sum(lwr), Fit = sum(fit), Upper = sum(upr))
                                  output %>% t %>% as.data.frame
                            })
    )
    

    【讨论】:

      【解决方案2】:

      找到了一个解决方案:有点靠不住,但它确实有效。

      在函数的开头,我建立了以下向量:

      costs <- c()
      lows <- c()
      fits <- c()
      highs <- c()
      

      这些与我输出的四列一致。然后,在循环结束时,在 -&gt; output 语句之后,我运行:

      costs[i] <- output[1]
      lows[i] <- output[2]
      fits[i] <- output[3]
      highs[i] <- output[4]
      

      由于某种原因,简单地将每个完整的 df 分配给一个 dfs 列表是行不通的;我必须逐个向量地做它。然后,一旦每个向量都与我的索引的全部范围一起存储,我就运行了这个:

      costs <- sapply(costs, unlist) %>% rowSums %>% as.data.frame
      lows <- sapply(lows, unlist) %>% rowSums %>% as.data.frame
      fits <- sapply(fits, unlist) %>% rowSums %>% as.data.frame
      highs <- sapply(highs, unlist) %>% rowSums %>% as.data.frame
      output <- cbind(costs, lows, fits, highs)
      output
      

      ...结束函数。总而言之真的很奇怪,但它确实有效。

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2019-11-12
        • 1970-01-01
        • 1970-01-01
        • 2020-07-12
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2019-10-09
        相关资源
        最近更新 更多