[R] Confusing fori or ifelse result in matrix manipulation
    Uwe Freier 
    uwe @end|ng |rom |re|er@de
       
    Sun Apr 24 17:05:55 CEST 2022
    
    
  
Hello,
sorry for the newbie question but I can't find out where I'm wrong.
A <- matrix(1:9,ncol=3)
x <- c(0,1,0)
M <- matrix(ncol=3,nrow=3)
for(i in 1:3) {
  M[,i] <- ifelse(x[i] == 0, A[,i], 0)
}
expected:
> M
      [,1] [,2] [,3]
[1,]    1    0    7
[2,]    2    0    8
[3,]    3    0    9
but the result is:
> M
      [,1] [,2] [,3]
[1,]    1    0    7
[2,]    1    0    7
[3,]    1    0    7
If I do it "manually":
> M[,1] <- A[,1]
> M[,2] <- 0
> M[,3] <- A[,3]
M is as expected, where is my misconception?
Thanks for any hint and best regards,
Uwe
    
    
More information about the R-help
mailing list