如何根据 R 中的 grepl 更改列中的值

How to change a value in a column dependent on a grepl in R

我想根据 data.frame.

中另一列的 grepl 中匹配的内容更改一列中的值

Data.frame 示例:

df
SHOT    CLASS     DATA_TEXT
shot1   missed     missed Jumper
shot2   made       made Three Point Jumper
shot3   made       made Jumper 

我一直在尝试的:

df$SHOT_TYPE <- as.vector(0) #create new variable

for (i in 1:length(df)) {
if(grepl("e Jumper", df$DATA_TEXT[i]))  { df$SHOT_TYPE <- "Jumper" 
} else if(grepl("d Jumper", df$DATA_TEXT[i]))  { df$SHOT_TYPE <- "Jumper" 
} else if(grepl("t Jumper", df$DATA_TEXT[i]))  { df$SHOT_TYPE <- "Three" } }

每次执行此方法 if statement 只会覆盖最后一个。

我目前的成绩:

df
SHOT    CLASS    DATA_TEXT                 SHOT_TYPE
shot1   missed   missed Jumper             Three
shot2   made     made Three Point Jumper   Three
shot3   made     made Jumper               Three

我希望结果看起来像什么:

df
SHOT    CLASS    DATA_TEXT                 SHOT_TYPE
shot1   missed   missed Jumper             Jumper
shot2   made     made Three Point Jumper   Jumper
shot3   made     made Jumper               Three

如有任何帮助,我们将不胜感激。如果需要任何进一步的信息,请告诉我。

这样的事情怎么样:

df$SHOT_TYPE <- ifelse(grepl('d Jumper|t Jumper', df$DATA_TEXT), 'Jumper',
                       ifelse(grepl('e Jumper', df$DATA_TEXT), 'Three', NA))

产生输出:

   SHOT  CLASS               DATA_TEXT SHOT_TYPE
1 shot1 missed           missed Jumper    Jumper
2 shot2   made made Three Point Jumper    Jumper
3 shot3   made            made Jumper      Three

注意:我将与这三种模式不匹配的列编码为 NA。您可以修改代码以满足您的需要。