It is essential that you understand the structure of the underlying design data. If it is a numeric variable then you'll get a slope and if it is a factor variable you'll get a step function ( ie a value for each level). As Glenn showed you can translate from one to the other. If nx is numeric then
fx=factor(nx)
will give you a factor variable. Here is an example
- Code: Select all
> nx=1:3
> str(nx)
int [1:3] 1 2 3
> fx=factor(nx)
> fx
[1] 1 2 3
Levels: 1 2 3
If you use a factor variable in a formula you get a column in the design matrix for each level:
- Code: Select all
> model.matrix(~fx,data.frame(fx=fx))
(Intercept) fx2 fx3
1 1 0 0
2 1 1 0
3 1 0 1
and if you use a numeric variable you get an intercept and a slope
- Code: Select all
> model.matrix(~nx,data.frame(nx=nx))
(Intercept) nx
1 1 1
2 1 2
3 1 3
If you want to change a factor into a numeric use
newnx=as.numeric(as.character(fx))
for example:
- Code: Select all
> newnx=as.numeric(as.character(fx))
> newnx
[1] 1 2 3
Note that in this case you could also use
- Code: Select all
> as.numeric(fx)
[1] 1 2 3
But in general that does not work as shown below:
- Code: Select all
> fx=factor(10:12)
> newnx=as.numeric(as.character(fx))
> newnx
[1] 10 11 12
> as.numeric(fx)
[1] 1 2 3
If you want to change which factor level is treated as the intercept use relevel
- Code: Select all
# here 10 is the intercept
> model.matrix(~fx,data.frame(fx=fx))
(Intercept) fx11 fx12
1 1 0 0
2 1 1 0
3 1 0 1
# now 11 is the intercept
> fx=relevel(fx,"11")
> model.matrix(~fx,data.frame(fx=fx))
(Intercept) fx10 fx12
1 1 1 0
2 1 0 0
3 1 0 1