Skip to content
Prev 43604 / 398525 Next

creating a factor

Simon Hosking <simon.hosking at general.monash.edu.au> writes:
factor(rep(1:2, c(7,3)))
It is not a good idea to use methods like cbind.data.frame directly.
Use the generic function cbind instead.  The point of having method
functions is to be able to choose the method that is appropriate to
the data.

If you have the matrix shown above stored as a matrix named mat then

cbind(factor(rep(1:2, c(7,3))), mat)

will work but it will also work if mat is a data frame.
[1] 1 1 1 1 1 1 1 2 2 2
Levels: 1 2
V1   V2
1  0.56 0.48
2  0.22 0.59
3  0.32 0.64
4  0.26 0.60
5  0.25 0.38
6  0.24 0.45
7  0.56 0.67
8  0.78 0.97
9  0.87 0.79
10 0.82 0.85
`data.frame':	10 obs. of  2 variables:
 $ V1: num  0.56 0.22 0.32 0.26 0.25 0.24 0.56 0.78 0.87 0.82
 $ V2: num  0.48 0.59 0.64 0.6 0.38 0.45 0.67 0.97 0.79 0.85
`data.frame':	10 obs. of  3 variables:
 $ factor(rep(1:2, c(7, 3))): Factor w/ 2 levels "1","2": 1 1 1 1 1 1 1 2 2 2
 $ V1                       : num  0.56 0.22 0.32 0.26 0.25 0.24 0.56 0.78 0.87 0.82
 $ V2                       : num  0.48 0.59 0.64 0.6 0.38 0.45 0.67 0.97 0.79 0.85