基于另一个因素替换一个特定因素

Replacing one specific factor based on another factor

R 版本 3.5.3 (2019-03-11)

大家好,我一直在处理一些棒球数据,并且一直在努力根据另一个因素替换一个因素... 假设我有:

Names <- c("name1", "name2", "name3", "name4", "name5")
batHand <- c("L", "S", "L","S", "R")
stats <- c(1, 2, 0, 1, 1)
pitchHand <- c("R", "L", "R", "R", "L")
baseballdf <- data.frame(Names, batHand, Stats, pitchHand)

我想将所有 S 切换到 pitchHand 的反面,所以它看起来像这样:

Names <- c("name1", "name2", "name3", "name4", "name5")
batHand <- c("L", "R", "L","L", "R")
stats <- c(1, 2, 0, 1, 1)
pitchHand <- c("R", "L", "R", "R", "L")
baseballdf2 <- data.frame(Names, batHand, Stats, pitchHand)

(实际数据框有 40,000 多行,因此手动切换行不通)

我主要使用 dplyr 并尝试了 mutate、replace、case_when 和 if_else 的多种变体,但无法完全弄清楚。 任何帮助将不胜感激。谢谢!

这是嵌套的方法 ifelse:

baseballdf %>% 
  mutate(batHand = ifelse(batHand != "S", batHand, ifelse(pitchHand == "R", "L", "R")))

case_when 可能更具可读性,但我们需要先将列更改为 character

baseballdf %>%
  mutate(
    batHand = as.character(batHand),
    batHand = case_when(
      batHand != "S" ~ batHand,
      pitchHand == "R" ~ "L",
      pitchHand == "L" ~ "R"
  ))