如何使用ddply为特定列的数据进行子集化?

Sol*_*Sol 3 r subset plyr

我想知道是否有一种简单的方法来实现我在下面描述的内容ddply.我的数据框描述了一个有两个条件的实验.参与者必须在选项AB之间进行选择,我们记录他们决定了多长时间,以及他们的回答是否准确.

ddply用来创造条件的平均值.该列nAccurate总结了每种情况下准确响应的数量.我也想知道他们花了多少时间来决定并在专栏中表达RT.但是,我想仅在参与者得到正确答案时才计算平均响应时间(即Accuracy==1).目前,以下代码只能计算所有回复的平均反应时间(准确且不准确).是否有一种简单的方法来修改它以获得仅在准确试验中计算的平均响应时间?

请参阅下面的示例代码,谢谢!

library(plyr)

# Create sample data frame. 
Condition = c(rep(1,6), rep(2,6))                               #two conditions
Response  = c("A","A","A","A","B","A","B","B","B","B","A","A")  #whether option "A" or "B" was selected
Accuracy  = rep(c(1,1,0),4)                                     #whether the response was accurate or not
RT        = c(110,133,121,122,145,166,178,433,300,340,250,674)  #response times
df        = data.frame(Condition,Response, Accuracy,RT)

head(df)

  Condition Response Accuracy  RT
1         1        A        1 110
2         1        A        1 133
3         1        A        0 121
4         1        A        1 122
5         1        B        1 145
6         1        A        0 166

# Calculate averages.  
avg <- ddply(df, .(Condition), summarise, 
                 N          = length(Response),
                 nAccurate  = sum(Accuracy),
                 RT         = mean(RT))

# The problem: response times are calculated over all trials. I would like
# to calculate mean response times *for accurate responses only*.

avg
  Condition N nAccurate       RT
          1 6         4 132.8333
          2 6         4 362.5000
Run Code Online (Sandbox Code Playgroud)

Jaa*_*aap 5

有了plyr,你可以这样做:

ddply(df,
      .(Condition), summarise, 
      N          = length(Response),
      nAccurate  = sum(Accuracy),
      RT         = mean(RT[Accuracy==1]))
Run Code Online (Sandbox Code Playgroud)

这给了:

   Condition N nAccurate     RT
1:         1 6         4 127.50
2:         2 6         4 300.25
Run Code Online (Sandbox Code Playgroud)

如果您使用data.table,那么这是另一种方式:

library(data.table)
setDT(df)[, .(N = .N,
              nAccurate = sum(Accuracy),
              RT = mean(RT[Accuracy==1])),
          by = Condition]
Run Code Online (Sandbox Code Playgroud)