回答編集履歴
1
テストスクリプト
test
CHANGED
@@ -1 +1,79 @@
|
|
1
1
|
case_whenの外にfactor()を置けばいいのでは?
|
2
|
+
|
3
|
+
|
4
|
+
|
5
|
+
# コメントを受けて
|
6
|
+
|
7
|
+
|
8
|
+
|
9
|
+
難しく考えることはないと思います。
|
10
|
+
|
11
|
+
|
12
|
+
|
13
|
+
```
|
14
|
+
|
15
|
+
library(dplyr)
|
16
|
+
|
17
|
+
df <- data.frame(a=seq(-20,20,6))
|
18
|
+
|
19
|
+
|
20
|
+
|
21
|
+
df %>% mutate(newvariable = case_when(
|
22
|
+
|
23
|
+
a <= -15 ~ "X",
|
24
|
+
|
25
|
+
a > -15 & a < 15 ~ "Y",
|
26
|
+
|
27
|
+
a >=15 ~ "C"
|
28
|
+
|
29
|
+
)) -> df
|
30
|
+
|
31
|
+
df %>% mutate(newvariable2 = factor(case_when(
|
32
|
+
|
33
|
+
a <= -15 ~ "X",
|
34
|
+
|
35
|
+
a > -15 & a < 15 ~ "Y",
|
36
|
+
|
37
|
+
a >=15 ~ "C"
|
38
|
+
|
39
|
+
))) -> df
|
40
|
+
|
41
|
+
```
|
42
|
+
|
43
|
+
|
44
|
+
|
45
|
+
実行結果
|
46
|
+
|
47
|
+
```
|
48
|
+
|
49
|
+
> df
|
50
|
+
|
51
|
+
a newvariable newvariable2
|
52
|
+
|
53
|
+
1 -20 X X
|
54
|
+
|
55
|
+
2 -14 Y Y
|
56
|
+
|
57
|
+
3 -8 Y Y
|
58
|
+
|
59
|
+
4 -2 Y Y
|
60
|
+
|
61
|
+
5 4 Y Y
|
62
|
+
|
63
|
+
6 10 Y Y
|
64
|
+
|
65
|
+
7 16 C C
|
66
|
+
|
67
|
+
> str(df)
|
68
|
+
|
69
|
+
'data.frame': 7 obs. of 3 variables:
|
70
|
+
|
71
|
+
$ a : num -20 -14 -8 -2 4 10 16
|
72
|
+
|
73
|
+
$ newvariable : chr "X" "Y" "Y" "Y" ...
|
74
|
+
|
75
|
+
$ newvariable2: Factor w/ 3 levels "C","X","Y": 2 3 3 3 3 3 1
|
76
|
+
|
77
|
+
>
|
78
|
+
|
79
|
+
```
|