r - 如何将函数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_
))
解决方案
您可以使用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
推荐阅读
- html - CSS 动画淡入/淡出问题
- python - fabric(2.5) 使用 SSH 连接不断询问密码
- javascript - 在 DOM 未渲染时使用 document.getElementById
- django - Django 找不到来自 Angular 的 url 模式请求
- java - 使用调度程序时的最佳实践
- lua - 放置代码说“尝试使用 'GetMouse' 索引 nil”,并且在需要它的代码之后我没有任何可变代码
- node.js - 在 React / Node 中运行最有效的网络爬虫
- regex - 正则表达式 - 量词可以跳过特定范围吗?
- python - 如何绘制以 x 轴为频率的 FFT 非周期性信号
- node.js - AWS Lambda:NodeJs 自定义层