'如果'用于基于条件的连续试验的平均值

时间:2017-05-22 17:32:50

标签: r data.table

我在下面有这个数据集,我想计算每mean(SACCADIC_RT)HITS一个佣金错误之前连续5个ID的{​​{1}}。

到目前为止,我已经尝试过:

CONDITION

但这不对。任何帮助将非常感激。谢谢!

我的数据如何显示的示例:

Data[, roll := Reduce('+', shift(HIT, 0:4)), by =list(ID, CONDITION)]

if (Data $roll == 5 & Data$COMISSION_ERROR[c(which(Data$roll == 5) +1), ] == 1)
 A<-  with(Data, mean(SACCADIC_RT[roll ==5]), by =list(ID, CONDITION))

输出的一个例子是:

structure(list(ID = c(1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 2L, 2L, 2L, 2L, 2L, 2L, 2L, 2L, 2L, 2L, 2L, 2L, 2L), X..TRIAL.. = c(183L, 54L, 26L, 3L, 100L, 11L, 52L, 8L, 10L, 21L, 32L, 2L, 13L, 87L, 95L, 111L, 28L, 65L, 40L, 19L, 28L, 45L, 197L, 115L, 65L, 24L, 1L, 77L, 90L, 89L, 104L, 116L, 29L, 41L), TRIAL_TYPE. = structure(c(2L, 1L, 2L, 2L, 2L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 2L, 2L, 2L, 1L, 2L, 1L, 2L, 2L, 1L, 2L, 2L, 2L, 1L, 1L, 2L, 1L, 1L, 1L, 1L, 1L, 2L, 1L), .Label = c("go", "nogo"), class = "factor"), CONDITION = structure(c(1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 2L, 2L, 2L, 2L, 2L, 1L, 1L, 1L, 1L, 1L, 1L, 2L, 2L, 2L, 2L, 2L, 2L, 2L, 2L, 2L, 2L), .Label = c("square_1", "square_2"), class = "factor"), X..COMMISSION_ERROR = c(1L, -1L, 1L, 1L, 1L, -1L, -1L, -1L, -1L, -1L, 1L, -1L, 0L, 1L, 1L, -1L, 0L, -1L, 0L, 0L, -1L, 1L, 1L, 1L, -1L, -1L, 1L, -1L, -1L, -1L, -1L, -1L, 1L, -1L), X..HITS. = c(-1L, 1L, -1L, -1L, -1L, 1L, 1L, 1L, 1L, 1L, -1L, 1L, -1L, -1L, -1L, 1L, -1L, 0L, -1L, -1L, 1L, -1L, -1L, -1L, 1L, 0L, -1L, 1L, 1L, 1L, 1L, 1L, -1L, 1L), SACCADIC_RT = c(175L, 259L, 365L, 346L, 287L, 164L, 244L, 223L, 183L, 234L, 221L, 183L, -1L, 228L, 274L, 305L, 309L, -1L, 199L, 207L, 257L, 169L, 350L, 321L, 298L, -1L, 183L, 225L, 305L, 210L, 199L, 175L, 99L, 104L)), .Names = c("ID", "X..TRIAL..", "TRIAL_TYPE.", "CONDITION", "X..COMMISSION_ERROR", "X..HITS.", "SACCADIC_RT"), class = "data.frame", row.names = c(NA, -34L))

@rconradin

1 个答案:

答案 0 :(得分:1)

您可以使用data.tablezoo个软件包的组合。

require(data.table); require(zoo)
data[  , A := rollmeanr(SACCADIC_RT, k = 5, fill = NA)][
      roll == 5 & lead(COMMISSION_ERROR) == 1]

rollmeanr来自zoo包。

另外,为了完整性,如果您只想指定三列,则可以使用

data[  , A := rollmeanr(SACCADIC_RT, k = 5, fill = NA)][
      roll == 5 & lead(COMMISSION_ERROR) == 1, .(ID, CONDITION, A)]