2017-02-16 136 views
0

问题是:创建一个函数,它接受一个数字向量。输出应该是具有运行平均值的矢量。输出向量的第i个元素应该是从1到i的输入向量中值的平均值。需要一些功能的帮助R

我的主要问题是在for循环,这是如下:

x1 <- c(2,4,6,8,10) 
    for (i in 2: length(x1)){ 
     ma <- sum(x1[i-1] , x1[i])/i 
     print(ma) 
     mresult <- rbind(ma) 
    } 
    View(ma) 

我知道一定有什么不对的。但我只是不确定它是什么。

+1

'mapply'尝试'mapply(函数(I)平均值(X1 [1:1]),1:长度(X1))?'。为了充分利用R,你需要学习'apply'函数 – Jean

+1

或者我认为'cumsum(x1)/(1:length(x1))'也可以工作 – Jean

+1

有人已经为你做了这个:'dplyr :: cummean ' –

回答

0

正如你已经注意到,有更有效的方法使用已有的函数和包来实现你正在尝试做的事情。但这里是你将如何去修复你的循环

x1 <- c(2,4,6,8,10) 
mresult = numeric(0) #Initiate mresult. Or maybe you'd want to initiate with 0 
for (i in 2: length(x1)){ 
    ma <- sum(x1[1:i])/i #You were originally dividing the sum of (i-1)th and ith value by i 
    print(ma) #This is optional 
    mresult <- c(mresult,ma) #Since you have only an array, there is no need to rbind 
} 
View(ma) #The last computed average 
View(mresult) #All averages 
+0

谢谢!在与我的代码进行比较后,我终于明白了为什么我错了。非常感激! – SeanZ