r - 如何使用 case_when 从列表中删除元素
问题描述
我有一个嵌套的字符串列表,我想在满足 grepl 条件时在新列中输入一个值,并且我还想从嵌套列表中删除该元素
我的列表如下(嵌套在数据框中)
list( "Normal Mucosa Throughout", "Mitotic Lesion- See Text Above",
"Normal",
c("Mitotic", "Hiatus Hernia"), "Normal Mucosa Throughout",
"HALO RFA to Barrett's oesophagus", "Barretts oesophagus",
c("Barrett's oesophagus ", "EMR"))
期望的结果:
FindingsAfterProcessing DiagnosisCode
Normal Mucosa Throughout other
C159
Normal other
Hiatus Hernia C159
Normal Mucosa Throughout other
HALO RFA to Barrett's oesophagus other
Barretts oesophagus other
Barrett's oesophagus other
EMR
我的case_when
myDf<-myDf%>%
mutate(DiagnosisCode = case_when(
grepl("mitotic|emr",tolower(myDf$OriginalFindings),ignore.case=TRUE) ~ "C159 - Malignant neoplasm oesophagus, unspecified - Oesophagus - unspecified",
TRUE ~ "other")
)
如何将此应用于嵌套列表并在找到后删除该元素?
解决方案
尝试map
从purrr
(你也可以只加载tidyverse
):
library(tidyverse)
df %>%
mutate(
DiagnosisCode = map(
FindingsAfterProcessing, ~ case_when(
any(grepl("mitotic", tolower(.x))) ~ "C159",
any(grepl("emr", tolower(.x))) ~ "EMR",
TRUE ~ "other")
),
FindingsAfterProcessing = map(
FindingsAfterProcessing, ~ .x[!grepl("mitotic|emr", tolower(.x))]
)
)
这里的输出是:
FindingsAfterProcessing DiagnosisCode
1 Normal Mucosa Throughout other
2 C159
3 Normal other
4 Hiatus Hernia C159
5 Normal Mucosa Throughout other
6 HALO RFA to Barrett's oesophagus other
7 Barretts oesophagus other
8 Barrett's oesophagus EMR
这不是 100% 对应于您想要的输出,但我猜您的输出中有错字?
我这样说是因为我的输出是基于您提供的列表;我已经把它变成了一个数据框列:
df <- data.frame(FindingsAfterProcessing = I(list( "Normal Mucosa Throughout", "Mitotic Lesion- See Text Above",
"Normal",
c("Mitotic", "Hiatus Hernia"), "Normal Mucosa Throughout",
"HALO RFA to Barrett's oesophagus", "Barretts oesophagus",
c("Barrett's oesophagus ", "EMR"))))
推荐阅读
- dax - 计算 AVERAGEX
- r - 如何将两个变量的特定值组合成一个新变量(?)
- python - 纠正格式错误的 JSON
- javascript - 删除数组内的内部数组的一项 - 反应原生
- react-native - 反应本机导航 Wix Navigation.pop 可能的未处理承诺拒绝(id:0):错误:无法执行堆栈命令
- javascript - Tilemap图层不与玩家碰撞
- chaquopy - 使用 chaquopy 4.0.0 将字符串写入特定目录
- python - Azure 函数 Python - 错误“未注册绑定类型‘blobTrigger’”
- dialogflow-es - Dialogflow 例程建议 - 触发从代理添加新例程
- jquery - 表单提交完成时如何隐藏加载器