Rのdplyrパッケージのmutate関数は新たに列を追加する関数です。
ここでは、mutate関数に文字列として与えた列に対して、paste関数で統合した結果を新たに追加する方法をお伝えします。
ここでは、mutate関数に文字列として与えた列に対して、paste関数で統合した結果を新たに追加する方法をお伝えします。
サンプルデータとして、統計的な学生の髪と目の色が収められているHairEyeColorを用います。
ただし、このサンプルデータはtableとなっておりますので、実際にはdata.frameに変換して用います。
library(dplyr)
data("HairEyeColor")
HairEyeColor %>% as.data.frame()
Hair Eye Sex Freq
1 Black Brown Male 32
2 Brown Brown Male 53
3 Red Brown Male 10
4 Blond Brown Male 3
5 Black Blue Male 11
6 Brown Blue Male 50
7 Red Blue Male 10
8 Blond Blue Male 30
9 Black Hazel Male 10
10 Brown Hazel Male 25
11 Red Hazel Male 7
12 Blond Hazel Male 5
13 Black Green Male 3
14 Brown Green Male 15
15 Red Green Male 7
16 Blond Green Male 8
17 Black Brown Female 36
18 Brown Brown Female 66
19 Red Brown Female 16
20 Blond Brown Female 4
21 Black Blue Female 9
22 Brown Blue Female 34
23 Red Blue Female 7
24 Blond Blue Female 64
25 Black Hazel Female 5
26 Brown Hazel Female 29
27 Red Hazel Female 7
28 Blond Hazel Female 5
29 Black Green Female 2
30 Brown Green Female 14
31 Red Green Female 7
32 Blond Green Female 8
このデータは、Hair列とEye列、Sex列が文字列となっておりますので、この列をpaste関数で結合して新たにNewCol列を追加するコードは次のようになります。
HairEyeColor %>%
(con) as.data.frame() %>%
(con) mutate(NewCol = paste(!!!rlang::syms(c("Hair", "Eye", "Sex")), sep="-"))
Hair Eye Sex Freq NewCol
1 Black Brown Male 32 Black-Brown-Male
2 Brown Brown Male 53 Brown-Brown-Male
3 Red Brown Male 10 Red-Brown-Male
4 Blond Brown Male 3 Blond-Brown-Male
5 Black Blue Male 11 Black-Blue-Male
6 Brown Blue Male 50 Brown-Blue-Male
7 Red Blue Male 10 Red-Blue-Male
8 Blond Blue Male 30 Blond-Blue-Male
9 Black Hazel Male 10 Black-Hazel-Male
10 Brown Hazel Male 25 Brown-Hazel-Male
11 Red Hazel Male 7 Red-Hazel-Male
12 Blond Hazel Male 5 Blond-Hazel-Male
13 Black Green Male 3 Black-Green-Male
14 Brown Green Male 15 Brown-Green-Male
15 Red Green Male 7 Red-Green-Male
16 Blond Green Male 8 Blond-Green-Male
17 Black Brown Female 36 Black-Brown-Female
18 Brown Brown Female 66 Brown-Brown-Female
19 Red Brown Female 16 Red-Brown-Female
20 Blond Brown Female 4 Blond-Brown-Female
21 Black Blue Female 9 Black-Blue-Female
22 Brown Blue Female 34 Brown-Blue-Female
23 Red Blue Female 7 Red-Blue-Female
24 Blond Blue Female 64 Blond-Blue-Female
25 Black Hazel Female 5 Black-Hazel-Female
26 Brown Hazel Female 29 Brown-Hazel-Female
27 Red Hazel Female 7 Red-Hazel-Female
28 Blond Hazel Female 5 Blond-Hazel-Female
29 Black Green Female 2 Black-Green-Female
30 Brown Green Female 14 Brown-Green-Female
31 Red Green Female 7 Red-Green-Female
32 Blond Green Female 8 Blond-Green-Female
R×dplyr 複数の列を文字列として指定し結合された列を追加する方法