根据其他列R

时间:2016-08-30 11:45:21

标签: r if-statement dataset conditional-statements

我有一个很大的数据集,在它的简短版本中看起来像这样:

> 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 $ TimeDiff中的某些值(仅S 88,S 66,S 77)分配正确,错误的响应和未命中。例如,如果S 88之前是S114或S104,并且该行的df $ TimeDiff小于710,则在df $ Accuracy中分配“不正确”。所以数据集看起来像这样:

> 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 

最好的方法是什么?

2 个答案:

答案 0 :(得分:1)

您可以使用ifelse

中的lagdplyr功能
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

答案 1 :(得分:0)

我们可以使用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))