根据其他列 R 中的不同值创建新列

Create a new column depending on different values in other columns R

我有一个大数据集,其简短版本如下所示:

> df
Stimulus    TimeDiff
S102        10332.4
S 66        1095.4
S103        2987.8
S 77        551.4
S112        3015.2
S 66        566.6
S114        5999.8
S 88        403.8
S104        4679.4
S 88        655.2

我想创建一个新列 df$Accuracy,我需要根据 df$Stimulus 和 df 中的某些值(仅 S 88、S 66、S 77)分配正确、不正确的响应和未命中$时间差异。例如,如果 S 88 之前是 S114 或 S104,并且该行的 df$TimeDiff 小于 710,则在 df$Accuracy 中分配 "incorrect"。所以数据集看起来像这样:

> df
Stimulus    TimeDiff     Accuracy
S102        10332.4      NA 
S 66        1095.4       NA
S103        2987.8       NA
S 77        551.4        NA
S112        3015.2       NA
S 66        566.6        NA
S114        5999.8       NA
S 88        403.8        incorrect
S104        4679.4       NA
S 88        655.2        incorrect 

最好的方法是什么?

您可以使用 ifelselag 来自 dplyr

的函数
library(dplyr) 
df$Accuracy <- with(df, ifelse(Stimulus %in% c('S88', 'S66', 'S77') &
                                   lag(Stimulus) %in% c('S114', 'S104') & 
                                           TimeDiff < 710, 'incorrect', NA))
df
#   Stimulus TimeDiff  Accuracy
#1      S102  10332.4      <NA>
#2       S66   1095.4      <NA>
#3      S103   2987.8      <NA>
#4       S77    551.4      <NA>
#5      S112   3015.2      <NA>
#6       S66    566.6      <NA>
#7      S114   5999.8      <NA>
#8       S88    403.8 incorrect
#9      S104   4679.4      <NA>
#10      S88    655.2 incorrect

我们可以为此使用 data.table 方法,它应该是有效的,因为我们正在分配 (:=)。

library(data.table)
setDT(df)[Stimulus %chin% c("S 88", "S 66", "S 77") & shift(Stimulus) %chin%
          c("S114", "S104") & TimeDiff < 710, Accuracy := "incorrect"]
df
#    Stimulus TimeDiff  Accuracy
# 1:     S102  10332.4        NA
# 2:     S 66   1095.4        NA
# 3:     S103   2987.8        NA
# 4:     S 77    551.4        NA
# 5:     S112   3015.2        NA
# 6:     S 66    566.6        NA
# 7:     S114   5999.8        NA
# 8:     S 88    403.8 incorrect
# 9:     S104   4679.4        NA
#10:     S 88    655.2 incorrect

数据

df <- structure(list(Stimulus = c("S102", "S 66", "S103", "S 77", "S112", 
"S 66", "S114", "S 88", "S104", "S 88"), TimeDiff = c(10332.4, 
1095.4, 2987.8, 551.4, 3015.2, 566.6, 5999.8, 403.8, 4679.4, 
655.2)), .Names = c("Stimulus", "TimeDiff"), class = "data.frame", 
row.names = c(NA, -10L))