如果名稱以“字串”開頭的任何變數等于特定字串,我嘗試將 mutate、case_when 和 if_any 組合起來創建一個變數 = 1。我無法弄清楚我在這些條件的組合中缺少什么。
我正在努力:
df <-data.frame(string1= c("a","b", "c"), string2= c("d", "a", "f"), string3= c("a", "d", "c"), id= c(1,2,3))
df <- df%>%
mutate(cod = case_when(if_any(starts_with("string") == "a" ~1 )))
uj5u.com熱心網友回復:
語法有點錯誤,但你很接近。請注意,它的if_any作業方式類似于across, so like this if_any(columns, condition),您應該使用function,\或~來指定條件。
df %>%
mutate(cod = case_when(if_any(starts_with("string"), ~ .x == "a") ~ 1))
string1 string2 string3 id cod
1 a d a 1 1
2 b a d 2 1
3 c f c 3 NA
轉載請註明出處,本文鏈接:https://www.uj5u.com/shujuku/521660.html
標籤:rdplyr条件语句变异
