在自动化报告算法 (R与Latex)一文中,讲述了如何用R与Latex生成自动化报告,Markdown也是一种自动化生成报告的语言,相比Latex,语句更简单。
在Rstudio中,可以直接进行R Markdown,其文件名后缀为.rmd。
本文通过分析题量与IRT模型计算精度的关系,利用R语句与Markdown结合生成自动化的分析报告。
*注意!如果不通过一些设定,无论是latex还是markdown都不识别中文,结果会报错。在本例中,需确保已安装rticles包,新建rmarkdown文件时从From Template中选择Ctex Document。
以下是代码:
---
title: "题量与模型计算精度的关系"
author: "Bene"
documentclass: ctexart
output:
rticles::ctex:
pdf_document: default
html_document: default
---
```{r setup, results='hide',include=FALSE}
knitr::opts_chunk$set(echo = TRUE)
```
```{r, echo=FALSE, results='hide', message = FALSE, warning = FALSE}
rm(list = ls()) #清空所有内存#
options(warn=-1) ##该语句用于禁止报告警告,与上方warning = FALSE意义相同##
##载入分析包###
library(TAM)
library(sirt)
library('ggplot2')
library(knitr)
options(digits=3)##设置小数点保留3位##
set.seed(123)##设置随机结果固定化,目的在于可以重现分析结果##
##构建模拟的分析数据###
N = 100 ##样本数量##
i = 50 ##题量##
b = stats::rnorm( i ) ##随机生成50道题的题目参数##
d= c(3:i) ##用于构建含有不同题量的模型##
y = stats::rnorm( N ) ##随机生成100个样本参数##
#####构建IRT能力分析function####
PersonAbility = function(d)
{
return( tam.wle(TAM::tam.mml(resp = sirt::sim.raschtype( y, sample(b,d)), constraint = "items"))$theta )
}
###在不同题量下,求测试者的IRT能力值##
din = as.data.frame(sapply(d, PersonAbility))
##以均方根误差(RMSE)作为误差衡量指标,构建RMSE的分析function##
rmse = function(y, h)
{
return(sqrt(mean((y - h) ^ 2)))
}
```
## 分析结果
### 在本例中, RMSE = sqrt(mean((原始观测值 - 预测值) ^ 2)), 其中预测值为线性模型中的预测值。下表为不同题量下的误差。
```{r, echo=FALSE}
###构建题量与误差对应的分析模型###
performance = data.frame()
for (d in 1:length(din))
{
fit = lm(y ~ din[,d])
performance = rbind(performance,
data.frame(Degree = d,
RMSE = rmse(din[,d], predict(fit))))
}
performance$Degree = performance$Degree + 2
###以下几句代码用于将长表格转化为短表格,以便显示美观###
#quantile(performance$Degree)
# 0% 25% 50% 75% 100%
# 3.0 14.8 26.5 38.2 50.0
sub1= subset(performance, performance$Degree >= 3 & performance$Degree <= 14)
sub2= subset(performance, performance$Degree >= 15 & performance$Degree <= 26)
sub3= subset(performance, performance$Degree >= 27 & performance$Degree <= 38)
sub4= subset(performance, performance$Degree >= 39 & performance$Degree <= 50)
xxx = cbind(sub1,sub2,sub3,sub4)
kable(xxx,col.names=c("题量","分析误差","题量","分析误差","题量","分析误差","题量","分析误差"),align='cccccccc')
```
## 图形
### 对结果作图,显示测试题量与分析误差的关系。
```{r, echo=FALSE}
ggplot(performance, aes(x = Degree, y = RMSE)) +
labs(x="Item number",y="Analytical error")+
geom_point() +
geom_line()
```
最终生成的PDF如下:
自动化生成的PDF报告