与我问的上一个问题相关(ggplot2 如何获得 2 个直方图,y 值 = 一个计数 / 两个计数的总和),我尝试编写一个函数,该函数将 data.frame 作为响应的输入几个参与者在几个条件下的时间(RT)和准确度(正确),并输出一个“汇总”data.frame,其中的数据像直方图一样聚合。这里的特殊性是我不想获得每个箱中响应的绝对数量,而是相对计数。
我所说的相对计数是对于直方图的每个 bin,该值对应于:
relative_correct = ncorrect / sum(ncorrect+nincorrect)
relative_incorrect = nincorrect / sum(ncorrect+nincorrect)
结果实际上接近于密度图,只是它不是每条曲线的总和等于 1,而是正确和不正确曲线的总和。
这是创建示例数据的代码:
# CREATE EXAMPLE DATA
subjectname <- factor(rep(c("obs1","obs2"),each=50))
Visibility <- factor(rep(rep(c("cond1","cond2"),each=25),2))
RT <- rnorm(100,300,50)
correct <- sample(c(rep(0,25),rep(1,75)),100)
my.data <- data.frame(subjectname,Visibility,RT,correct)
首先,我需要定义一个稍后在 ddply 中使用的函数
histRTcounts <- function(df) {out = hist(df$RT, breaks=seq(5, 800, by=10), plot=FALSE)
out = out$counts}
然后是 main 函数(有 2 个小问题阻止它在函数内部工作,请参见带有 ????? 的行,但在函数外部,此代码有效)。
relative_hist_count <- function(df, myfactors) {
require(ggplot2)
require(plyr)
require(reshape2)
# ddply it to get one column for each bin of the histogram
myhistRTcounts <- ddply(df, c(myfactors,"correct"), histRTcounts)
# transform it in long format
myhistRTcounts.long = melt(myhistRTcounts, id.vars =c(myfactors,"correct"), variable.name="bin", value.name = 'mycount')
# rename the bin names with the ms value they correspond to
levels(myhistRTcounts.long$bin) <- seq(5, 800, by=10)[-1]-5
# make them numeric and not a factor anymore
myhistRTcounts.long$bin = as.numeric(levels(myhistRTcounts.long$bin))[myhistRTcounts.long$bin]
# cast to have count_correct and count_incorrect as columns
# ??????????????????????? problem when putting that into a function
# Here I was not able to figure out how to combine myfactors to the other variables in the call
myhistRTcount.short = dcast(myhistRTcounts.long, subjectname + Visibility + bin ~ correct)
names(myhistRTcount.short)[4:5] <- c("countinc","countcor")
# compute relative counts
myhistRTcounts.rel <- ddply(myhistRTcount.short, myfactors, transform,
incorrect = countinc / sum(countinc+countcor),
correct = countcor / sum(countinc+countcor)
)
myhistRTcounts.rel = subset(myhistRTcounts.rel,select=c(-countinc,-countcor))
myhistRTcounts.rel.long = melt(myhistRTcounts.rel, id.vars = c(myfactors,"bin"), variable.name = 'correct', value.name = 'mycount')
# ??????????????????????? idem here, problem when putting that into a function to call myfactors
ggplot(data=myhistRTcounts.rel.long, aes(x=bin, y=mycount, color=factor(correct))) + geom_line() + facet_grid(Visibility ~ subjectname) + xlim(0, 600) + theme_bw()
return(myhistRTcounts.rel.long)
将其应用于数据的调用
new.df = relative_hist_count(my.data, myfactors = c("subjectname","Visibility"))
所以首先,我需要你的帮助才能使它作为一个函数工作,并有可能在 dcast() 和 ggplot() 中使用 myfactors 变量。
但更重要的是,我几乎可以肯定这个函数可以用更少的步骤以更优雅、最直接的方式编写。
预先感谢您的帮助!