對于ifelse陳述句,使用函式和直接資料操作運行多個引數相當容易,如下所示:
#### Load Library ####
library(tidyverse)
#### Run Multiple Ifelse Statements ####
iris %>%
mutate(New.Sepal.Width = ifelse(Sepal.Width > 3.5,
"Large",
ifelse(Sepal.Width < 3,
sqrt(Sepal.Width),
NA)))
但是我似乎不明白如何對 in 做同樣的case_when事情dplyr。如果我運行類似這樣的代碼:
iris %>%
mutate(New.Sepal.Width = case_when(
Sepal.Width >= 3.5 ~ "Large",
Sepal.Width <= 3 ~ "sqrt(Sepal.Width)",
Sepal.Width > 3 | Sepal.Width < 3.5 ~ "NA"
))
它按字面意思列印,sqrt(Sepal.Width)而不是平方根。如果我將其指定為普通功能:
iris %>%
mutate(New.Sepal.Width = case_when(
Sepal.Width >= 3.5 ~ "Large",
Sepal.Width <= 3 ~ sqrt(Sepal.Width), # change here
Sepal.Width > 3 | Sepal.Width < 3.5 ~ "NA"
))
這最終給了我其他問題:
Error in `mutate()`:
! Problem while computing `New.Sepal.Width = case_when(...)`.
Caused by error in `case_when()`:
Run `rlang::last_error()` to see where the error occurred.
有沒有解決的辦法?
uj5u.com熱心網友回復:
如果您檢查?case_when,您可以看到:
RHS 不需要是邏輯的,但所有 RHS 必須評估為相同型別的向量。
所以你需要你的 RHS 只是性格。您可以通過用 轉換sqrt(Sepal.Width)為字符向量as.character并替換NA為 來實作NA_character_。
你可以做:
iris %>%
mutate(New.Sepal.Width = case_when(
Sepal.Width >= 3.5 ~ "Large",
Sepal.Width <= 3 ~ as.character(sqrt(Sepal.Width)),
Sepal.Width > 3 | Sepal.Width < 3.5 ~ NA_character_
))
請注意,在dplyr's development version中,并且據說從dplyr 1.1以后開始,case_when不再需要NA預先指定,所以這將起作用:
iris %>%
mutate(New.Sepal.Width = case_when(
Sepal.Width >= 3.5 ~ "Large",
Sepal.Width <= 3 ~ as.character(sqrt(Sepal.Width)),
Sepal.Width > 3 | Sepal.Width < 3.5 ~ NA
))
轉載請註明出處,本文鏈接:https://www.uj5u.com/net/517957.html
