我有一個這樣的資料集。
ID Yr Month
1 3 NA
2 4 23
3 NA 46
4 1 19
5 NA NA
我喜歡創建一個新列,Age其中
Case1 : Age = Year, if Month is missing
Case2 : Age = Year Month/12 , if Year and Month are not missing
Case3 : Age = Month/12 , if Year is missing
Case4 : Age = NA, if both Year and Month are missing.
最終的預期資料集應如下所示。
ID Yr Month Age
1 3 NA 3
2 4 23 5.91
3 NA 46 3.83
4 1 19 2.58
5 NA NA NA
我可以用 30 行代碼來完成這個,但我正在尋找一個簡單有效的解決方案來解決這個問題。任何建議,非常感謝,提前致謝。
uj5u.com熱心網友回復:
您可以在case_when陳述句中包含條件。
library(dplyr)
df %>%
mutate(Age = case_when(is.na(Month) & is.na(Yr) ~ NA_real_,
is.na(Month) ~ as.numeric(Yr),
is.na(Yr) ~ Month/12,
TRUE ~ Yr Month/12))
# ID Yr Month Age
#1 1 3 NA 3.000000
#2 2 4 23 5.916667
#3 3 NA 46 3.833333
#4 4 1 19 2.583333
#5 5 NA NA NA
轉載請註明出處,本文鏈接:https://www.uj5u.com/qita/316386.html
上一篇:在QUERY中應用IF邏輯
