使用ddply()聚合相对直方图计数

时间:2013-01-31 10:10:04

标签: r ggplot2 histogram plyr reshape2

与上一个问题(ggplot2 how to get 2 histograms with the y value = to count of one / sum of the count of both)相关,我尝试编写一个函数,它将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}

然后是主要功能(有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变量。

但更重要的是,我几乎可以肯定这个功能可以用更简单的方式写得更优雅,步骤更少。

提前感谢您的帮助!

2 个答案:

答案 0 :(得分:0)

这可能有助于设置数据吗?

countfun <- function(x,...) {
  res <- hist(x,plot=FALSE,...)
  data.frame(counts=res$counts,
             break1=res$breaks[-length(res$breaks)],
             break2=res$breaks[-1])
}

library(plyr)
plot.dat <- ddply(my.data,.(Visibility),function(df){
  res <- ddply(df,.(correct),function(df2) {countfun(df2$RT,breaks=seq(100, 600, by=10))})
  res$freq2 <- res$counts/nrow(df)
  res
})

您可能需要将整个parseevalas.formula内容推广到任意因素。我现在没有时间。

但是,如果您计划进行概括,最好修改hist函数以接受用作计数因子的参数。

答案 1 :(得分:0)

感谢Roland,我没有考虑编写自制的hist函数。请在下面找到:

RelativeHistRT <- function (df, breaks = seq(5,800,10)) 
{
  distrib.correct   = hist(df$RT[df$correct==1], breaks, right=FALSE, plot=FALSE)
  distrib.incorrect = hist(df$RT[df$correct==0], breaks, right=FALSE, plot=FALSE)

  n.total = sum(distrib.correct$counts) + sum(distrib.incorrect$counts)

  data.frame(bin_mids  = distrib.correct$mids,
         correct   = distrib.correct$counts / n.total,
         incorrect = distrib.incorrect$counts / n.total)
}

并将其应用到我原来的data.frame并获得我想要的内容:

myhistRTcounts <- ddply(my.data, .(subjectname,Visibility), RelativeHistRT)

这确实要短得多,而且正是我所寻找的。