R语言测试题-循环-求均值

Report your results for the following questions by using R.
(a) Generate 1000 data points from a normal distribution with mean 3 and sd = 1. Store the 1000 datapoints as a vector whose name is n.v. Report the first 10 elements of the vector.
(b) Calculate the average values of the first k values in n.v, where k = 1, 2, 3, 4, …, 1000. Collect the results as a vector whose name is ave.v. [Note the length of ave.v is 1000.]
这个问题是求前1个,前2个,前k+1个均值吗?用循环语句吗?
(c) Generate three figures by plotting the first 10 values, 100 values, 1000 values of ave.v. Combine the three figures into one figure, and report the figure. [Hint: Search “plot multiple figures in R” in Google.]
(d) Repeat steps 1 to 3 to generate another figure for 1000 data points from a bernouli distribution with prob = 0.4. [Hint: Check rbern]
(e) Explain What you observe in question 6(c) and 6(d).

由于要重复abc步骤,可以将上述三步封装到一个函数中,然后作图,参考以下代码:

getwd()
library(Rlab)
n.v<-rnorm(1000,mean=3,sd=1)
f<-function(x){
ave.v=c()
for (k in 1:length(x)){
    ave.v<-c(ave.v,sum(x[1:k])/k)
}
data=matrix(c(ave.v[1:11],ave.v[1:101],ave.v[1:1001]),ncol=3)
return (data)
}
d=f(n.v)
m.v<-rbern(1000,0.4)
m=f(m.v)
par(mfrow=c(1,2))
matplot(d,type='b',pch=1,col=1:3)
legend("topright", legend = 1:3, col=1:3, pch=1)
matplot(m,type='b',pch=1,col=1:3)
legend("topright", legend = 1:3, col=1:3, pch=1)

如对你有帮助,请点击一下采纳按钮。