LoginSignup
2
2

More than 5 years have passed since last update.

R {dplyr} 0.5.0 新関数

Posted at

case_when関数

dplyrをversionを新しくしたついでに何が追加されたかみていると
case_when関数というものが追加されてので使い方を確認しておく(URL)。

例えば

case_when(
  iris$Species == "setosa" ~ "1",
  iris$Species ==  "versicolor" ~ "2",
  iris$Species == "virginica" ~ "3" 
)

と書くと実行結果は以下の

 [1] "1" "1" "1" "1" "1" "1" "1" "1" "1" "1" "1" "1" "1" "1" "1" "1" "1" "1" "1" "1" "1" "1" "1" "1" "1"
 [26] "1" "1" "1" "1" "1" "1" "1" "1" "1" "1" "1" "1" "1" "1" "1" "1" "1" "1" "1" "1" "1" "1" "1" "1" "1"
 [51] "2" "2" "2" "2" "2" "2" "2" "2" "2" "2" "2" "2" "2" "2" "2" "2" "2" "2" "2" "2" "2" "2" "2" "2" "2"
 [76] "2" "2" "2" "2" "2" "2" "2" "2" "2" "2" "2" "2" "2" "2" "2" "2" "2" "2" "2" "2" "2" "2" "2" "2" "2"
[101] "3" "3" "3" "3" "3" "3" "3" "3" "3" "3" "3" "3" "3" "3" "3" "3" "3" "3" "3" "3" "3" "3" "3" "3" "3"
[126] "3" "3" "3" "3" "3" "3" "3" "3" "3" "3" "3" "3" "3" "3" "3" "3" "3" "3" "3" "3" "3" "3" "3" "3" "3"

ようになる。また、

case_when(
  iris$Sepal.Length < 5.5 ~ "1",
  iris$Sepal.Length < 6.5 ~ "2",
  iris$Sepal.Length >= 6.5~ "3" 
)

以下のように実行結果がなる。

  [1] "1" "1" "1" "1" "1" "1" "1" "1" "1" "1" "1" "1" "1" "1" "2" "2" "1" "1" "2" "1" "1" "1" "1"
 [24] "1" "1" "1" "1" "1" "1" "1" "1" "1" "1" "2" "1" "1" "2" "1" "1" "1" "1" "1" "1" "1" "1" "1"
 [47] "1" "1" "1" "1" "3" "2" "3" "2" "3" "2" "2" "1" "3" "1" "1" "2" "2" "2" "2" "3" "2" "2" "2"
 [70] "2" "2" "2" "2" "2" "2" "3" "3" "3" "2" "2" "2" "2" "2" "2" "1" "2" "3" "2" "2" "2" "2" "2"
 [93] "2" "1" "2" "2" "2" "2" "1" "2" "2" "2" "3" "2" "3" "3" "1" "3" "3" "3" "3" "2" "3" "2" "2"
[116] "2" "3" "3" "3" "2" "3" "2" "3" "2" "3" "3" "2" "2" "2" "3" "3" "3" "2" "2" "2" "3" "2" "2"
[139] "2" "3" "3" "3" "2" "3" "3" "3" "2" "3" "2" "2"

カテゴリー変数を作るには便利な関数だと思う。ただし、返り値がリストで帰ってきているのが注意点ぐらいだと思う。

2
2
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
2
2