Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

R number of items to replace is not a multiple of replacement length / results however correct

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

like image 641
tfp Avatar asked Feb 28 '14 15:02

tfp


1 Answers

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

like image 177
Christopher Louden Avatar answered Nov 07 '22 07:11

Christopher Louden