我正在嘗試將一些復雜的類別組合在一起,這些類別與字串的開頭相似。
這是第一個 case_when 子句的示例,您可以看到它很長(為簡潔起見,我編輯了字串)
有沒有辦法撰寫一個 case_when 陳述句,它將所有以“條件”開頭的值分組?(這也適用于以“心理健康等”開頭的其余條款。)
謝謝你們!
mutate(condition=case_when(health_conditions == 'Conditions ABC' | health_conditions == 'Conditions DEF' | health_conditions =='HIJ' | health_conditions == 'Conditions KLM, Parkinsons)' | health_conditions == 'Conditions NOP' ~ 'Conditions')
uj5u.com熱心網友回復:
我們可以使用正則運算式grepl/str_detect來組合這些情況
library(dplyr)
library(stringr)
df1 %>%
mutate(condition = case_when(str_detect(health_conditions,
"^Conditions")|health_conditions == "HIJ" ~ 'Conditions'))
或者另一種選擇是 startsWith
df1 %>%
mutate(condition = case_when(startsWith(health_conditions,
"Conditions")|health_conditions == "HIJ" ~ "Conditions"))
uj5u.com熱心網友回復:
case_when()有點代碼味道。以下基本 R 習語更簡單并使用%in%:
conds <- c("Conditions DEF", "HIJ") # add extra as required
df1$condition[df1$health_conditions %in% conds] <- "Condition"
或者,正如另一個答案中所建議的,正則運算式可能會有所幫助:
df1$condition[grepl("Conditions", df1$health_conditions)] <- "Condition"
轉載請註明出處,本文鏈接:https://www.uj5u.com/yidong/409166.html
標籤:
