问题是:创建一个接受数字向量的函数。输出应该是具有运行平均值的向量。输出向量的第i个元素应该是从1到i的输入向量中的值的平均值。
我的主要问题是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)
我知道它一定有问题。但我不确定它是什么。
答案 0 :(得分: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