- 追加された行はこのように表示されます。
- 削除された行は
このように表示されます。
!演習や検証用のダミーデータを作る
Rには、変数のすべてかけ合わせた組み合わせ(デカルト積)を生成する、'''expand.grid()'''関数があるが、tydyrには'''crossing()'''が同様の機能を果たす。'''tidyr::expand_grid()'''のラッパー関数。
以下の3つが組み合わせていろいろ使えそう。
* tydyr::crossing()
* tydyr::expand()
* tydyr::nesting()
!expand_grid()
> expand.grid(a = c(1,2,3), b=c(4,5,6))
a b
1 1 4
2 2 4
3 3 4
4 1 5
5 2 5
6 3 5
7 1 6
8 2 6
9 3 6
! crossing(): 与えた変数の組み合わせを返す
> Branch = c("東","西", "南", "北")
> Fruits = c("Apple", "Orange", "Banana")
> crossing(Branch, Fruits)
# A tibble: 12 x 2
Branch Fruits
<chr> <chr>
1 西 Apple
2 西 Banana
3 西 Orange
4 東 Apple
5 東 Banana
6 東 Orange
7 南 Apple
8 南 Banana
9 南 Orange
10 北 Apple
11 北 Banana
12 北 Orange
!expand() : 可能な変数の組み合わせを返す(実在しない組み合わせも含まれる)
> all = crossing(Branch, Fruits)
> all %>% expand(Fruits)
# A tibble: 3 x 1
Fruits
<chr>
1 Apple
2 Banana
3 Orange
> all %>% expand(Branch, Fruits)
# A tibble: 12 x 2
Branch Fruits
<chr> <chr>
1 西 Apple
2 西 Banana
3 西 Orange
4 東 Apple
5 東 Banana
6 東 Orange
7 南 Apple
8 南 Banana
9 南 Orange
10 北 Apple
11 北 Banana
12 北 Orange
!nesting() : 実際に存在する組み合わせのみを抽出する
> all %>% expand(nesting(Branch))
# A tibble: 4 x 1
Branch
<chr>
1 西
2 東
3 南
4 北
> all %>% expand(nesting(Branch, Fruits))
# A tibble: 12 x 2
Branch Fruits
<chr> <chr>
1 西 Apple
2 西 Banana
3 西 Orange
4 東 Apple
5 東 Banana
6 東 Orange
7 南 Apple
8 南 Banana
9 南 Orange
10 北 Apple
11 北 Banana
12 北 Orange
:参考:
* https://tidyr.tidyverse.org/reference/expand.html