Reputation: 91
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
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..
Upvotes: 8
Views: 54164
Reputation: 1225
or try this if you want to create five vectors of Y's.
set.seed(101)
lambda_j <- rgamma(1000,1,1)
Y <- matrix(NA, nrow=1000, ncol=5)
for (j in 1:ncol(Y)) {
for(i in 1:nrow(Y)) {
Y[,j] <- rpois(1000,lambda_j)
}
}
Upvotes: 0
Reputation: 7592
which()
can return a vector if there are multiple matches. For example:
which((1:12)%%2 == 0) # which are even?
Is matrix$col_b[i]
unique? The results may still look correct. Notice what happens in this case:
x <- 1:2
x[1] <- 3:4
x
Also, 1:b-1
does not give you the numbers from 1
to b - 1
but the number from 1
to b
, all minus 1
:
b <- 10
1:b-1
You need parentheses to force the subtraction first: 1:(b - 1)
.
Upvotes: 6