R:如何仅针对行的子集和条件向现有数据框添加新列

R: How to add a new column to an existing dataframe ONLY for a subset of rows and with a condition

我想根据其他列的值添加一个名为 "real_rt" 的新列。

数据框中感兴趣的列是:

"Real_rt" 应基于从 StimOnset 中减去 RT,仅当 RT 中的值 > 0 时(否则它应保持为 0)。 但是,此计算应仅针对 go 试验(第 "trail_type" 列)执行。

我知道如何添加新列以及如何制作 for 循环和 if-statemanet(因为我认为这就是我在这里需要的),但我不知道如何将这 3 个组合到为了得到我想要的。任何想法将不胜感激。

这应该可以引导您朝着正确的方向前进。

df <- data.frame(X = c(1, 0, 2, 4),
                 Y = c(2, -1, 0, 5))

df$Z <- ifelse(df$Y > 0, df$X - df$Y, 0)
df
#  X  Y  Z
#1 1  2 -1
#2 0 -1  0
#3 2  0  0
#4 4  5 -1

我喜欢将 mutate 与 tidyverse 包中的 case_when 结合用于此类事情:

require(tidyverse)

df <- data.frame(StimOnset = c(1, 0, 2, 4),
                 RT = c(2, -1, 0, 5),
                 trial_type = c("go", "nogo", "go", "nogo"))

df <- df %>% 
  mutate(
   Real_rt = case_when(
     trial_type == "go" & RT > 0 ~ StimOnset - RT,
     TRUE ~ 0
    )
  )
df
StimOnset RT trial_type Real_rt
1         1  2         go      -1
2         0 -1       nogo       0
3         2  0         go       0
4         4  5       nogo       0