首页 > 解决方案 > 每次我尝试显示表格结果时打印标题

问题描述

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 的变量添加到数据集中的一行中。但是,当我打印时,每次都会出现列标题:

#   Theta Expectation       Sd Skewness
# 1     1         1.5 1.322876 1.727838
# 
#   Theta Expectation        Sd Skewness
# 2     2   0.6666667 0.6236096  2.06173

我怎样才能解决这个问题?

标签: r

解决方案


函数中的所有计算都是矢量化的,因此您可以在没有循环的情况下输入矢量。

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))

推荐阅读