I know there have been already some threads on this, however going through those I was not able to figure out what the problem might be - please forgive me for that..
I am trying to run the code
for (i in 1:a){
matrix$new_column[i]<-which(matrix[i,1:b-1]==matrix$col_b[i])
}
What I am attempting is: For the matrix of a lines and b columns, in each line´s columns 2 to b-1, find the one that contains the same value as the one in column b (there is always such a value) and write the according column number into the *new_column*
My Code keeps throwing the error
Warning in matrix$new_column[i] <- which(matrix[i, : number of items to replace is not a multiple of replacement length
However, the result is completely correct. I have tried
- creating the *new_column* filled with 0s first
- changing the end indices from a to a-1 or a+1
As said, the outcome is correct, however I feel I should not be getting the warning message if I did everything correctly, so I´m really grateful for any advice on how to fix this.
Finally, don´t ask me why I chose 1:b-1 when I wanted to go from 2 to b-1, I just saw that when I would use 2:b-1, it would acutally begin in column 3..
which()
can return a vector if there are multiple matches. For example:Is
matrix$col_b[i]
unique? The results may still look correct. Notice what happens in this case:Also,
1:b-1
does not give you the numbers from1
tob - 1
but the number from1
tob
, all minus1
:You need parentheses to force the subtraction first:
1:(b - 1)
.or try this if you want to create five vectors of Y's.