根据另一列中的模式填充一列

Populate a column based on a pattern in another column

我有一个 DF,我试图根据字符串中的模式是否存在来填充列。

A      B     
E3Y12
E3Y45
E3Y56
c1234
c56534
c3456

我想检查 A 是否包含字符串 'E3Y' 并用“This one”填充 B 列,或者它是否不包含该模式“That one”

我已经在 case_when() 和 ifelse() 语句中尝试了 dplyr starts_with 但没有用,因为它必须是 select 函数的一部分。

您可以使用 str_detect() 来评估字符串是否包含特定模式,然后使用 ifelse 非常简单:

library(dplyr)
tibble( A = c(
"E3Y12",
"E3Y45",
"E3Y56",
"c1234",
"c56534",
"c3456")) %>% 
  mutate(B = ifelse(stringr::str_detect(A, "E3Y"), "This one", "That one"))

尝试:

library(dplyr)

df %>% 
  mutate(B = ifelse(grepl("E3Y", A), "This one", "That one"))

输出为:

# A tibble: 6 × 2
  A      B       
  <chr>  <chr>   
1 E3Y12  This one
2 E3Y45  This one
3 E3Y56  This one
4 c1234  That one
5 c56534 That one
6 c3456  That one

用过

df <- structure(list(A = c("E3Y12", "E3Y45", "E3Y56", "c1234", "c56534", 
"c3456"), B = c(NA, NA, NA, NA, NA, NA)), class = c("tbl_df", 
"tbl", "data.frame"), row.names = c(NA, -6L))