R語言 case when 函式

2021-10-07 14:22:53 字數 3192 閱讀 4951

要點有兩個

不匹配的時候會返回 na,而不是保持不變

根據順序進行條件判斷,順序很重要

下面這段**,

x <- 1:50

case_when(

x %% 35 == 0 ~ "fizz buzz",

x %% 5 == 0 ~ "fizz",

x %% 7 == 0 ~ "buzz",

true ~ as.character(x)

)

如果不包含true ~ as.character(x),會返回

[1] na          na          na          na          "fizz"      na         

[7] "buzz" na na "fizz" na na

[13] na "buzz" "fizz" na na na

[19] na "fizz" "buzz" na na na

[25] "fizz" na na "buzz" na "fizz"

[31] na na na na "fizz buzz" na

[37] na na na "fizz" na "buzz"

[43] na na "fizz" na na na

[49] "buzz" "fizz"

如果不包含true ~ as.character(x),不滿足前面幾個條件的數字到了這裡會被轉成 character,因此不會返回 na

x <- 1:50

case_when(

x %% 35 == 0 ~ "fizz buzz",

x %% 5 == 0 ~ "fizz",

x %% 7 == 0 ~ "buzz",

true ~ as.character(x)

)#> [1] "1" "2" "3" "4" "fizz" "6"

#> [7] "buzz" "8" "9" "fizz" "11" "12"

#> [13] "13" "buzz" "fizz" "16" "17" "18"

#> [19] "19" "fizz" "buzz" "22" "23" "24"

#> [25] "fizz" "26" "27" "buzz" "29" "fizz"

#> [31] "31" "32" "33" "34" "fizz buzz" "36"

#> [37] "37" "38" "39" "fizz" "41" "buzz"

#> [43] "43" "44" "fizz" "46" "47" "48"

#> [49] "buzz" "fizz"

# like an if statement, the arguments are evaluated in order, so you must

# proceed from the most specific to the most general. this won't work:

case_when(

true ~ as.character(x),

x %% 5 == 0 ~ "fizz",

x %% 7 == 0 ~ "buzz",

x %% 35 == 0 ~ "fizz buzz"

)#> [1] "1" "2" "3" "4" "5" "6" "7" "8" "9" "10" "11" "12" "13" "14" "15"

#> [16] "16" "17" "18" "19" "20" "21" "22" "23" "24" "25" "26" "27" "28" "29" "30"

#> [31] "31" "32" "33" "34" "35" "36" "37" "38" "39" "40" "41" "42" "43" "44" "45"

#> [46] "46" "47" "48" "49" "50"

可以配合verb使用

starwars %>%

select(name:mass, gender, species) %>%

mutate(

type = case_when(

height > 200 | mass > 200 ~ "large",

species == "droid" ~ "robot",

true ~ "other"

))

case_when可以用在和tidyverse庫以外的函式一起使用

case_character_type <- function(height, mass, species) 

case_character_type(150, 250, "droid")

#> [1] "large"

case_character_type(150, 150, "droid")

#> [1] "robot"

R語言 case when 函式

要點有兩個 不匹配的時候會返回 na,而不是保持不變 根據順序進行條件判斷,順序很重要 下面這段 x 1 50 case when x 35 0 fizz buzz x 5 0 fizz x 7 0 buzz true as.character x 如果不包含true as.character x ...

R語言 函式

函式是一組組合在一起以執行特定任務的語句。r語言具有大量內建函式,使用者可以建立自己的函式。在r語言中,函式是乙個物件,因此r語言直譯器能夠將控制傳遞給函式,以及函式完成動作所需的引數。該函式依次執行其任務並將控制返回到直譯器以及可以儲存在其他物件中的任何結果。函式定義 使用關鍵字函式建立r語言的函...

函式專題 CASE WHEN

case when 語句 一 概述 1.這個語句使用起來像decode函式加強版,9i之後的多重條件分支語句,decode配合例如sign類似的函式也能達到case when的效果,但是case when效率更高,需要注意的是,每個值返回的型別需要一致。2.case語句可以實現if語句的功能。3.c...