第5章 tidyverse(dplyr)で再現 ・ ノック 62 / 100 ・ [[000 - はじめに(使い方と目次)|目次]]<br>
← 前 [[061 - 行を絞る]] ・ 次 → [[063 - 列を選ぶ]]
> [!info] filter() にカンマで条件を並べると「かつ」の意味になります
> `filter()` では、条件をカンマで区切って複数並べることができます。カンマは「**かつ(AND)**」を意味します。たとえば `filter(iris, Species == "setosa", Sepal.Length > 5.5)` は「Species が setosa、かつ Sepal.Length が 5.5 より大きい行」を取り出します。
>
> Rベースでは `iris[iris$Species == "setosa" & iris$Sepal.Length > 5.5, ]` のように `&` を使って書いていました。dplyr ではカンマで区切るか、明示的に `&` を書くかのどちらでも同じ結果になります。「または(OR)」の条件を使いたいときは `|` を使います。
## 問題
`iris` から「Species が setosa、かつ Sepal.Length が 5.5 より大きい」行を取り出し、先頭3行を表示してみましょう。
> [!tip] ヒント
> `filter()` にカンマで区切って2つの条件を並べます。「より大きい」は `>` 記号を使います。
> [!success]- 回答を見る
> ```r
> library(dplyr)
> filter(iris, Species == "setosa", Sepal.Length > 5.5) |> head(3)
> ```
> ```
> Sepal.Length Sepal.Width Petal.Length Petal.Width Species
> 1 5.8 4.0 1.2 0.2 setosa
> 2 5.7 4.4 1.5 0.4 setosa
> 3 5.7 3.8 1.7 0.3 setosa
> ```
> Rベースでは `iris[iris$Species == "setosa" & iris$Sepal.Length > 5.5, ]` と書いていましたが、`filter()` にカンマで条件を並べると同じ結果が得られます。