r语言 - dapply:结果正确,但结构混乱



我有一个data.frame mydf,其中包含来自27个主题的数据。有两个预测因子,congruent(2个水平)和offset(5个水平),所以总共有10个条件。27名被试在每种条件下每人测试20次,共观察10*27*20 = 5400次。RT为响应变量。结构如下所示:

> str(mydf)
'data.frame':   5400 obs. of  4 variables:
 $ subject  : Factor w/ 27 levels "1","2","3","5",..: 1 1 1 1 1 1 1 1 1 1 ...
 $ congruent: logi  TRUE FALSE FALSE TRUE FALSE TRUE ...
 $ offset   : Ord.factor w/ 5 levels "1"<"2"<"3"<"4"<..: 5 5 1 2 5 5 2 2 3 5 ...
 $ RT       : int  330 343 457 436 302 311 595 330 338 374 ...

我使用daply()来计算每个受试者在10种情况下的mean RT:

myarray <- daply(mydf, .(subject, congruent, offset), summarize, mean = mean(RT))

结果看起来就像我想要的那样,即一个3d数组;也就是说,5个表(每个offset条件一个)显示了每个受试者在congruent=FALSEcongruent=TRUE条件下的平均值。

然而,如果我检查myarray的结构,我得到一个令人困惑的输出:

List of 270
 $ : num 417
 $ : num 393
 $ : num 364
 $ : num 399
 $ : num 374
 ... 
 # and so on
 ...
 [list output truncated]
 - attr(*, "dim")= int [1:3] 27 2 5
 - attr(*, "dimnames")=List of 3
  ..$ subject  : chr [1:27] "1" "2" "3" "5" ...
  ..$ congruent: chr [1:2] "FALSE" "TRUE"
  ..$ offset   : chr [1:5] "1" "2" "3" "4" ...

这看起来与plyr包中的原型ozone数组的结构完全不同,尽管它的格式非常相似(3维,只有数值)。

我想通过aaply计算这个数组的一些进一步的汇总信息。确切地说,我想计算每个主题和偏移量的一致和不一致的平均值之间的差异。

然而, aaply() 最基本的应用已经像 aaply(myarray,2,mean) 返回无意义的输出:

FALSE  TRUE 
   NA    NA 
Warning messages:
1: In mean.default(piece, ...) :
  argument is not numeric or logical: returning NA
2: In mean.default(piece, ...) :
  argument is not numeric or logical: returning NA

我不知道,为什么daply()函数返回如此奇怪的结构化输出,从而阻止任何进一步使用aaply。任何形式的帮助都是善意的感谢,我坦率地承认,我几乎没有任何经验的plyr包。

由于您没有包括您的数据,因此很难确定,但我试图使一个虚拟设置您的str()。你可以用ddply的两种用法做你想做的(我猜)。首先是平均数,然后是平均数之差。

#Make dummy data
mydf <- data.frame(subject = rep(1:5, each = 150), 
  congruent = rep(c(TRUE, FALSE), each = 75), 
  offset = rep(1:5, each = 15), RT = sample(300:500, 750, replace = T))
#Make means
mydf.mean <- ddply(mydf, .(subject, congruent, offset), summarise, mean.RT = mean(RT))
#Calculate difference between congruent and incongruent
mydf.diff <- ddply(mydf.mean, .(subject, offset), summarise, diff.mean = diff(mean.RT))
head(mydf.diff)
#   subject offset  diff.mean
# 1       1      1  39.133333
# 2       1      2   9.200000
# 3       1      3  20.933333
# 4       1      4  -1.533333
# 5       1      5 -34.266667
# 6       2      1  -2.800000

最新更新