I have a discrete factor, of length 79.
[1] 4 6 6 4 6 1 6 4 1 6 1 4 6 1 1 1 6 6 6 6 6 4 1 6 6 4 6 6 1 1 6 4 6 1 6 6 4 4
[39] 6 6 4 1 1 4 1 1 6 1 1 6 6 1 1 6 4 1 1 6 1 6 6 1 6 6 6 6 1 1 1 1 6 1 1 1 1 1
[77] 6 6 1
Levels: 1 4 6
I am trying to cbind this discrete factor to a large matrix with dimensions: 79 rows by 1921 columns. I am told that my end result should be the original matrix with columns added to it, but I'm not sure how I should approach this problem. Thanks in advance.
This is the code I was given to cbind the factor to the matrix:
dd1 = mat.x
for(v in levels(X)){
nv = rep(0, length(X))
nv[X==v] = 1
dd1 = cbind(dd1, nv)
}
I get this warning message:
Warning messages:
1: In cbind(dd1, nv) :
number of rows of result is not a multiple of vector length (arg 2)
2: In cbind(dd1, nv) :
number of rows of result is not a multiple of vector length (arg 2)
3: In cbind(dd1, nv) :
number of rows of result is not a multiple of vector length (arg 2)
I think your problem was just a typo. Using the sample data
mat.x <- matrix(1, nrow=17, ncol=4)
X <- factor(sample(c(4,6,10), 17, replace=T))
this code worked
dd1 = mat.x
for(v in levels(X)){
nv = rep(0, length(X))
nv[X==v] = 1
dd1 = cbind(dd1, nv)
}
Note that I had to change nv[y==v] = 1
to nv[X==v] = 1
because you did not define y
anywhere in your problem.