在 R 中使用 case_when 与 str_replace_all 替换多种模式的文本字符串

问题描述 投票:0回答:1

我对 R 基本上是全新的。我正在尝试编写我目前拥有的代码的更精简版本,它只是重复一堆 str_replace_all 函数。我觉得必须有更好的方法来做到这一点。

我正在清理地址并尝试匹配一些拼写错误并将其替换为正确的州名称。

我让它工作的一个笨拙方法如下:

CA_messy <- c("CAtypo1|CAtypo2|CAtypo3|CAtypo4")
LA_messy <- c("LAtypo1|LAtypo2")


alldata_cleaned$StateClean <- str_replace_all(alldata$State, CA_messy, "CALIFORNIA")
alldata_cleaned$StateClean <- str_replace_all(alldata$StateClean, LA_messy, "LOUISIANA")
alldata_cleaned$StateClean <- str_replace_all(alldata$StateClean, "NEVEDA","NEVADA")

但我不喜欢一遍又一遍地重写东西。 str_replace_all 也会做部分单词(例如,如果我想用“CALIFORNIA”替换“CA”,它也会替换全名中的 CA,给出“CALIFORNIALIFORNIA”。)我也尝试过 case_when,但无法实现工作:

alldata_cleaned2 <- alldata_cleaned %>%
  mutate(StateClean = case_when(
    State == CA_messy ~ "CALIFORNIA",
    State == LA_messy ~ "LOUISIANA",
    State == "NEVEDA" ~ "NEVADA",
    TRUE ~ State
  ))

只有 NEVEDA 的最后一个替代品正在工作。有没有办法通过将向量输入参数来进行 case_when 替换?我一直在摆弄语法,但似乎无法让它工作。我在 SO 上看到了很多类似的问题,并一直在尝试实现它们,但没有成功。谢谢!

r
1个回答
0
投票

您正在寻找

%in%
运算符,假设
CA_messy
LA_messy
是向量:

alldata_cleaned2 <- alldata_cleaned %>%
  mutate(StateClean = case_when(
    State %in% CA_messy ~ "CALIFORNIA",
    State %in% LA_messy ~ "LOUISIANA",
    State == "NEVEDA" ~ "NEVADA",
    TRUE ~ State
  ))

您还可以在

case_when
中使用正则表达式,如下所示:

alldata_cleaned2 <- alldata_cleaned %>%
  mutate(StateClean = case_when(
    grepl("[CA Pattern]", State) ~ "CALIFORNIA",
    grepl("[LA Pattern]", State) ~ "LOUISIANA",
    grepl("[NV Pattern]", State) ~ "NEVADA",
    TRUE ~ State
  ))
© www.soinside.com 2019 - 2024. All rights reserved.