2017-02-16 143 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