【问题标题】:daply: Correct results, but confusing structuredaply:结果正确,但结构混乱
【发布时间】:2013-06-17 23:11:22
【问题描述】:

我有一个 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() like 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 包几乎没有任何经验。

【问题讨论】:

  • 如果没有您可以使用的实际数据,很难确定,但您所描述的内容都不会让我想到使用daplyaaply。我觉得所有这一切都可以只使用ddply 来完成(可能还有dlplydcast,这取决于你希望事情的结局如何)。
  • summarise 返回一个数据框,您现在正尝试将其放入数组中。最好不要使用数组,但如果必须,请使用daply(mydf, .(subject, congruent, offset), function(df) mean(df$RT))

标签: r plyr


【解决方案1】:

由于您没有包含您的数据,因此很难确定,但我尝试在您的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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-08-07
    • 1970-01-01
    • 2021-04-03
    相关资源
    最近更新 更多