首页 > 解决方案 > 如何将函数startsWith应用于几种模式?

问题描述

我有一个数据框。我想为创建依赖于其他列的列编写条件。这里是:

tab <- tibble::tribble(
  ~dataset_id,  ~type,
     "Site4H",      268,
     "Site4D",      479,
     "SIte8H",      345,
     "Site8D",      567,
     "Site8K",      507
  )
library(dplyr)
tab %>%
  mutate(state = case_when(
    endsWith(dataset_id, "H") ~ "healthy",
    endsWith(dataset_id, "D") ~ "disease",
    TRUE                      ~ NA_character_
  ))

标签: rdataframestringr

解决方案


您可以使用grepl/str_detect来匹配模式。

要与“H”或“K”匹配,您可以将其写为:

library(dplyr)

tab %>%
  mutate(state = case_when(
    grepl('H|K', dataset_id) ~ "healthy",
    endsWith(dataset_id, "D") ~ "disease",
    TRUE                      ~ NA_character_
  ))

#   dataset_id bacteria state  
#  <chr>         <int> <chr>  
#1 Site4H          268 healthy
#2 Site4D          479 disease
#3 SIte8H          345 healthy
#4 Site8D          567 disease
#5 Site8K          567 healthy

推荐阅读