# How to Convert Factor to Dummy Variables

``````> dput(head(final,10))
structure(list(Y = c(93.433, 104.456, 163.792, 125.249, 146.837,
78.196, 52.192, 191.33, 75.02, 145.785), X1 = c(5.9701, 9.3506,
9.718, 14.1317, 9.9278, 1.9318, 2.2236, 12.612, 13.8961, 8.1844
), X2 = c(6.047, 9.4063, 9.4967, 13.9422, 10.0581, 1.6575, 1.8749,
12.3052, 13.7316, 8.2732), X3 = c(8.1105, 8.365, 16.8862, 14.8049,
14.1477, 15.9753, 12.0362, 16.5604, 8.1691, 16.4479), x4 = c(1.70843,
0.34726, 4.76446, 2.19965, 2.80567, 7.58081, 5.59927, 3.56611,
-1.10324, 4.76204), x5 = c(1, 1, 1, 2, 1, 1, 3, 1, 2, 1)), row.names = c(NA,
10L), class = "data.frame")
``````

x5 is my factor variable, which has type 1, 2, 3. Now I want to create x6 and x7 such that:

Types x6 x7
type 1 0 0
type 2 1 0
type 3 0 1

How to do?

``````set.seed(42)
(somedata <- data.frame(X1=runif(10),
X5=factor(sample.int(3,10,replace=TRUE,prob = c(.7,.2,.1)))))
(extra <- model.matrix(~ X5 - 1, data = somedata))
(extrax <- extra[,-1])
cbind(somedata,extrax)``````

It doesn't work for me. When I run your code, it gives me a column vector, that is the same as x5.

(extra <- model.matrix(~ x5 - 1, data = final))
x5
1 1
2 1
3 1
4 2
5 1
6 1
7 3
8 1
9 2
10 1
11 1
12 2
13 2
14 2
15 1
16 1
17 3
18 1
19 1
20 1
21 1
22 1
23 1
24 3
25 1
26 1
27 1
28 1
29 1
30 1
31 1
32 1
33 2
34 1
35 1
36 2
37 3
38 1
39 3
40 2
41 1
42 3
43 1
44 1
45 3
46 1
47 1
48 1
49 3
50 1
51 2
52 2
53 1
54 1
55 3
56 1
57 1
58 1
59 2
60 1
61 2
62 1
63 1
64 3
65 1
66 3
67 1
68 1
69 1
70 1
71 1
72 2
73 1
74 1
75 1
76 1
77 2
78 1
79 2
80 1
81 1
82 3
83 2
84 1
85 1
86 1
87 1
88 2
89 1
90 2
91 2
92 1
93 1
94 1
95 1
96 1
97 2
98 2
99 1
100 1
101 1
102 3
103 2
104 1
105 1
106 1
107 3
108 1
109 2
110 1
111 1
112 1
113 3
114 2
115 1
116 1
117 1
118 1
119 2
120 1
121 2
122 3
123 1
124 2
125 2
126 2
127 2
128 1
129 1
130 1
attr(,"assign")
[1] 1

Recommend you run my code as is on my example data (you did not provide example data)
Then you can try to analyse relevant difference between your input data and mine.

Good luck !

This topic was automatically closed 21 days after the last reply. New replies are no longer allowed.

If you have a query related to it or one of the replies, start a new topic and refer back with a link.