我有一個資料框,我想根據資料框中的其他現有列(“th”和“br”)創建一個新列(“path”)。如果“th”中的值為“NA”,我想根據“ce”和“br”列創建新列。
可以使用以下代碼創建可重現的資料樣本:
df <- structure(list(
th = c(3, 1, NA, 2, 2, 0, 3, 3, 0, 2, 3, 2, 1, NA, 3, 4, 3, 3, 1, 3),
br = c(1, 2, 4, 1, 2, 2, 1, 2, 2, 5, 4, 1, 1, 2, 1, 5, 2, 1, 1, 1),
ce = c(2, 3, 2, 0, 1, 0, 2, 1, 1, 1, 1, 0, 0, 1, 2, 0, 0, 1, 1, 2)),
row.names = c(NA, 20L), class = "data.frame")
我已經使用 if 和 else 陳述句嘗試了以下代碼:
df <- df %>% if(!is.na(th)) {
mutate(path = case_when(
(th %in% c(0:2) & br %in% c(0:3) ~ "Low"),
(th %in% c(3:5) & br %in% c(0:3) ~ "Intermediate"),
(th %in% c(3:5) & br %in% c(4:6) ~ "High")))
} else {
mutate(path = case_when(
(ce %in% c(0:1) & br %in% c(0:3) ~ "Low"),
(ce %in% c(1:3) & br %in% c(3) ~ "Intermediate"),
(ce %in% c(2:3) & br %in% c(4:6) ~ "High")))
}
這會導致錯誤“if (.) !is.na(th) else { 中的錯誤:條件的長度 > 1”
代碼有什么問題?關于如何改進代碼或替代解決方案的任何建議?
uj5u.com熱心網友回復:
嘗試這個:
df %>%
mutate(path = ifelse(!is.na(th),
case_when(
(th %in% c(0:2) & br %in% c(0:3) ~ "Low"),
(th %in% c(3:5) & br %in% c(0:3) ~ "Intermediate"),
(th %in% c(3:5) & br %in% c(4:6) ~ "High")),
case_when(
(ce %in% c(0:1) & br %in% c(0:3) ~ "Low"),
(ce %in% c(1:3) & br %in% c(3) ~ "Intermediate"),
(ce %in% c(2:3) & br %in% c(4:6) ~ "High"))))
轉載請註明出處,本文鏈接:https://www.uj5u.com/qiye/483642.html
上一篇:谷歌表單時間戳日期
