r - 每次我尝试显示表格结果时打印标题
问题描述
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
我怎样才能解决这个问题?
解决方案
函数中的所有计算都是矢量化的,因此您可以在没有循环的情况下输入矢量。
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))
推荐阅读
- python - 寻找一种检查数学运算的方法
- html - 如何使难度条动态化?
- android - 安装 Flutter 和 Dart 后 Build.Gradle 文件损坏
- reactjs - React Native Button onPress 性能
- javascript - 不变违规:RN原生模块不可用
- swagger - NestJS / Swagger - 没有得到完整的描述
- javascript - 为什么我可以在设置状态之前访问嵌套对象,但之后却不能?
- c - 难题:如何让 ADC 采样与 POSIX 计时器同步?
- c++ - Id 退出状态的问题
- syncfusion - 如何使用 Syncfusion ej2 在上下文菜单中创建关闭功能