R number of items to replace is not a multiple of

2020-03-16 03:48发布

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..

2条回答
Ridiculous、
2楼-- · 2020-03-16 04:37

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).

查看更多
一夜七次
3楼-- · 2020-03-16 04:44

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)
  }
}
查看更多
登录 后发表回答