R - 具有与一个代码关联的多个文本值的重新编码列

R - Recoding column with multiple text values associated with one code

我正在尝试重新编码列以确定员工的班次。

资料比较乱,我要找的词必须从文中提取出来。我一直在尝试使用 if 语句、stringrdplyr 包的各种路径,但无法弄清楚如何让它们协同工作。

我有这行代码,但是 str_match 没有产生 true/false 值。

Data$Shift <- if(str_match(Data$Unit, regex(first, ignore_case = TRUE))) {
    print("First Shift")
  } else {
    print("Lame")
  }

重新编码工作正常,但我有多个值需要重新编码,想了解是否有办法将 stringr 合并到重新编码函数中。

Data$Shift1 <- recode(Data$Unit, "1st" = "First Shift")

目前,必须从列中提取文本以包含 1st、First 或 First Shift 的 first。我的数据看起来像单位列,我想将其重新编码到移位列中:

Unit                        Shift
Detention, Third Shift      Third Shift
D, 3rd Shift                Third Shift
1st                         First Shift
first shift                 First Shift
First Shift                 First Shift
1st shift                   First Shift
1st Shifft                  First Shift `

我建议在 dplyr 内使用 greplcase_when

library(dplyr)

Data %>% 
  mutate(Shift = case_when(grepl("first|1st", Unit, ignore.case = TRUE) ~ "First Shift",
                           grepl("third|3rd", Unit, ignore.case = TRUE) ~ "Third Shift",
                           TRUE                                         ~ "Neither"))
  • mutate 创建我们的新列 Shift

  • grepl return 是一个逻辑向量,无论它是否匹配模式。在这种情况下,我使用的模式是 "first|1st"| 字符表示 OR,照原样检查 "first" 或“1st”。

  • case_when 的工作方式类似于多个 "if" 语句,允许我们将逻辑放在一起(类似于 SQL 语法)。 case_when 的最后一行是我们这里的安全网....如果 Unit 的值不包含第 1 或第 3 班次,它将 return "Neither",所以我们知道要进一步调查。

如果您没有最新版本的 dplyr (>0.7.3),那么 case_when 可能不适合您。如果是这样,我们可以用嵌套的 ifelse.

链替换 case_when
Data %>% 
  mutate(Shift = ifelse(grepl("first|1st", Unit, ignore.case = TRUE),
                        "First Shift",
                        ifelse(grepl("third|3rd", Unit, ignore.case = TRUE),
                               "Third Shift",
                               "Neither")))

不太漂亮,但应该是相同的结果,因为我们在 grepl 中使用的模式是互斥的。

保持简单:

Data$shift[grepl("3rd", Data$shift)] <- "Third Shift"
Data$shift[grepl("1st", Data$shift)] <- "First Shift"