Word-filled函数的循环求和

时间:2014-06-19 06:12:28

标签: r function loops dataframe sum

我已经设置了列表

Dow30 <- c("MMM","AXP","T","BA","CAT","CVX","CSCO","DD","XOM","GE","GS","HD","INTC","IBM","JNJ","JPM", "MCD","MRK","MSFT","NKE","PFE","PG","KO","TRV","UTX","UNH","VZ","V","WMT","DIS")

我想通过我的函数SumProfitOnly每个项目(单独地,在引号中)循环,然后每个项目的<数字>返回一起总结

这个手写方法让我得到了我正在寻找的最终答案......

print(SumProfitOnly("DIS") + SumProfitOnly("MMM") + SumProfitOnly("AXP") + SumProfitOnly("T") + SumProfitOnly("BA") + SumProfitOnly("CAT") + SumProfitOnly("CVX") + SumProfitOnly("CSCO") + SumProfitOnly("DD") + SumProfitOnly("XOM") + SumProfitOnly("GE") + SumProfitOnly("GS") + SumProfitOnly("HD") + SumProfitOnly("INTC") + SumProfitOnly("IBM") + SumProfitOnly("JNJ") + SumProfitOnly("JPM") + SumProfitOnly("MCD") + SumProfitOnly("MRK") + SumProfitOnly("MSFT") + SumProfitOnly("NKE") + SumProfitOnly("PFE") + SumProfitOnly("PG") + SumProfitOnly("KO") + SumProfitOnly("TRV") + SumProfitOnly("UTX") + SumProfitOnly("UNH") + SumProfitOnly("VZ") + SumProfitOnly("V") + SumProfitOnly("WMT"))

...但我正在努力让更快的功能工作。

我的(失败)努力:

1)基于this相关问题 -

rate <- function(n) {
    result <- lapply(n, function(i) data.frame(n = i, calculated = as.vector(SumProfitOnly(i))))

    return(do.call(rbind, result))
}

print(rate(Dow30))

这会产生数据框中的每个结果(以及原始文本自动收录器,没有引号)。看起来像这样:

      n calculated
1   MMM       4.01
2   AXP       3.31
3     T      -1.05
4    BA      -0.77
5   CAT       3.40
6   CVX       1.90
7  CSCO       2.46
8    DD       3.95
9   XOM       2.03
etc., etc., etc.

我试图围绕事情推动总和,但要么忽略 sum函数,要么出现错误,就像这次尝试改变印刷品一样:

print(sum(rate(Dow30)), na.rm = FALSE) 

给出错误:

Error in FUN(X[[1L]], ...) : 
  only defined on a data frame with all numeric variables

2)基于另一个回答的问题:

for (n in Dow30)
{
printer[n] = print(SumProfitOnly(n))    
}

产生这个:

[1] 4.01
[1] 3.31
[1] -1.05
[1] -0.77
[1] 3.4
[1] 1.9
[1] 2.46
[1] 3.95
[1] 2.03
etc., etc., etc., 

在这里,再一次,在函数内外添加sum是不成功的,因为它只返回&#34; sum&#34;我列表中的最后一个值

0 个答案:

没有答案