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

时间:2015-09-16 15:04:21

标签: r subset plyr

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

我使用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

2 个答案:

答案 0 :(得分:5)

使用plyr,您可以按以下方式执行此操作:

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

这给出了:

   Condition N nAccurate     RT
1:         1 6         4 127.50
2:         2 6         4 300.25

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

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

答案 1 :(得分:1)

使用dplyr包:

library(dplyr)
df %>%
  group_by(Condition) %>%
  summarise(N = n(),
            nAccurate = sum(Accuracy),
            RT = mean(RT[Accuracy == 1]))