results <- data.frame(Theta = rep(0,20), Expectation = rep(0,20), Sd = rep(0,20), Skewness = rep(0,20))
for (theta in 1:20){
lindley.plot(theta)
}我有创建数据集的代码,然后我尝试将每个θ的变量添加到数据集中的一行中。但是,当我打印它时,每次都会出现列标题:
# Theta Expectation Sd Skewness
# 1 1 1.5 1.322876 1.727838
#
# Theta Expectation Sd Skewness
# 2 2 0.6666667 0.6236096 2.06173我怎么才能解决这个问题?
发布于 2020-02-25 06:08:57
函数中的所有计算都是向量化的,因此可以在没有循环的情况下输入向量。
lindley.plot <- function(theta){
expectation = (theta + 2)/(theta^2 + theta)
sd = (sqrt(theta^2 + 4*theta + 2))/(theta^2 + theta)
skewness = (4*theta^3 + 12*theta^2 + 12*theta + 4)/(theta^2 + 4*theta + 2)^(3/2)
return(data.frame(theta, expectation, sd, skewness))
}
lindley.plot(1:20)
# theta expectation sd skewness
# 1 1 1.50000000 1.32287566 1.727838
# 2 2 0.66666667 0.62360956 2.061730
# 3 3 0.41666667 0.39965263 2.320856
# 4 4 0.30000000 0.29154759 2.522038
# 5 5 0.23333333 0.22852182 2.681433
# 6 6 0.19047619 0.18747638 2.810390
# ...如果函数变得更加复杂和非矢量化,请使用lapply输入向量的每个元素。
do.call(rbind, lapply(1:20, lindley.plot))https://stackoverflow.com/questions/60388240
复制相似问题