【发布时间】:2014-02-10 19:53:43
【问题描述】:
我有这个函数来获取 IRT 包 sirt 返回的对象,并为用户可以指定的一组项目绘制项目响应函数:
plotRaschIRF <- function(x,items=NULL,thl=-5,thu=5,thi=.01,D=1.7) {
if (!class(x)=="rasch.mml") stop("Object must be of class rasch.mml")
thetas <- seq(thl,thu,thi)
N <- length(thetas)
n <- length(x$item$b)
tmp <- data.frame(item=rep(1:n,each=N),theta=rep(thetas,times=n),b=rep(x$item$b,each=N))
probs <- exp(D*(tmp[,2]-tmp[,3]))/(1+exp(D*(tmp[,2]-tmp[,3])))
dat <- data.frame(item=rep(1:n,each=N),theta=rep(thetas,times=n),b=rep(x$item$b,each=N),p=probs)
#dat$item <- factor(dat$item,levels=1:n,labels=paste0("Item",1:n))
if (is.null(items)) {
m <- min(10,n)
items <- 1:m
if (10<n) warning("By default, this function will plot only the first 10 items")
}
if (length(items)==1) {
title="Item Response Function"
} else {
title="Item Response Functions"
}
dat2 <- subset(dat,eval(quote(eval(item,dat) %in% items)))
dat2$item <- factor(dat2$item,levels=unique(dat2$item),labels=paste0("Item",unique(dat2$item)))
out <- ggplot(dat2,aes(x=theta,y=p,group=item)) +
geom_line(aes(color=dat2$item),lwd=1) + guides(col=guide_legend(title="Items")) +
theme_bw() + ggtitle(title) + xlab(expression(theta)) +
ylab("Probability") + scale_x_continuous(breaks=seq(thl,thu,1))
print(out)
}
但它似乎卡在我开始使用 ggplot2 之前的那一行(我将一列 dat2 转换为一个因子)或 ggplotting 本身——不太确定是哪一行。我收到错误消息"Error in eval(expr, envir, enclos) : object 'dat2' not found".
我尝试按照here 的建议阅读this,但要么这是一个不同的问题,要么我就是不明白。当我逐行遍历它时,该功能工作正常。非常感谢任何帮助!
【问题讨论】:
-
这一行:
subset(dat,eval(quote(eval(item,dat) %in% items)))真的只是想选择dat的行,其中item列的值在向量items中吗? -
避免心痛,不要在函数中使用
subset。它旨在用于交互式使用。你为什么不dat2 <- dat[dat$item %in% items, ] -
是的,这就是它的全部意义,实际上我最初有@BrodieG 的建议,但我最初认为错误消息是由于这条线引起的,并进行了整个评估狂欢试图修复它在意识到不是这样之前(或者,至少,后续行仍然导致相同的错误消息)。我不认为问题出在这里——函数会在崩溃之前通过这一行(我可以让它打印在那可怕的行和下一行之间的东西)。
-
最好使用
fortify方法,ggplot2实现lm对象。一旦你编写了一个创建数据框的 fortify.raschmml 方法,你就可以更容易地调用ggplot -
我没听说过
fortify,谢谢提醒