java if else嵌套_替代嵌套If Else语句
在@thelatemail's回答的基础上,结合@mt1022's注释使用 case_when 和 mutate ,这是一个完整的例子,使用 stringr 中的函数进行文本工作 .
library(dplyr)
library(stringr)
# make vector of pitch sequence data
PITCH_SEQ_TX
# make another variable of the number of pitches in each sequence
# this is just so we have two variables for a df
NUM_PITCHES
# make a df
BB
# create the recoded pitch sequence variable - PITCH_SEQ_TX_UPDATED
BB %>%
dplyr::mutate(PITCH_SEQ_TX_UPDATED =
dplyr::case_when(
stringr::str_detect(string = PITCH_SEQ_TX, pattern = "^[CFLMST]{2,}") ~ "Two strikes",
stringr::str_detect(string = PITCH_SEQ_TX, pattern = "^B{3,}") ~ "Three balls"
)
)
# A tibble: 5 x 3
PITCH_SEQ_TX NUM_PITCHES PITCH_SEQ_TX_UPDATED
1 SSSC 4 Two strikes
2 FFBB 4 Two strikes
3 BBSSC 5
4 BBBSB 5 Three balls
5 CBSFFFS 7