0
votes

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)

2
No-can-do with a matrix. Perhaps a data frame? Matrix columns must all be the same classRich Scriven
Did you actually try cbind or not? I don't see why mat <- cbind(mat, vec) shouldn't work (where mat is your matrix and vec is your factor vector)David Arenburg
That would work, but the factored vector will no longer be factoredRich Scriven
Hi, I edited my original post to include warning message and code that I ran.Brian Lee
Did you confirm length(X)==nrow(mat.x)?MrFlick

2 Answers

1
votes

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.

0
votes

all elements in a matrix must be the same class. use data.frame or data.table instead

 data.frame(vec, mat)