[R] Confusing fori or ifelse result in matrix manipulation

Ebert,Timothy Aaron tebert @end|ng |rom u||@edu
Mon Apr 25 16:01:15 CEST 2022


A <- matrix(1:9,ncol=3)
x <- c(0,1,0)
M <- matrix(ncol=3,nrow=3)
M<-A
for(i in 1:3) {
  if(x[i]){
    M[,i] <-0
    }
  } 
}
M

The outcome you want is to set all of the middle column values to zero. So I used x as a logical in an if test and when true everything in that column is set to zero.

Your approach also works but you must go through each element explicitly.
A <- matrix(1:9,ncol=3)
x <- c(0,1,0)
M <- matrix(ncol=3,nrow=3)
for(j in 1:3){
  for(i in 1:3){
    ifelse(x[i]==1, M[j,i]<-0, M[j,i]<-A[j,i])
  }
}
M



Tim

-----Original Message-----
From: R-help <r-help-bounces using r-project.org> On Behalf Of Uwe Freier
Sent: Sunday, April 24, 2022 11:06 AM
To: r-help using r-project.org
Subject: [R] Confusing fori or ifelse result in matrix manipulation

[External Email]

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

______________________________________________
R-help using r-project.org mailing list -- To UNSUBSCRIBE and more, see https://urldefense.proofpoint.com/v2/url?u=https-3A__stat.ethz.ch_mailman_listinfo_r-2Dhelp&d=DwICAg&c=sJ6xIWYx-zLMB3EPkvcnVg&r=9PEhQh2kVeAsRzsn7AkP-g&m=eyJm06tVDfKvtMDgz6oIWM-WVdoW3Szzb5G6rq0cCO_cB6ljj2x80E4oRkt3Vgba&s=K2RWPvtxaxwigGGH2oOrg8qiDWC5KTu60b8Wjybwsg4&e=
PLEASE do read the posting guide https://urldefense.proofpoint.com/v2/url?u=http-3A__www.R-2Dproject.org_posting-2Dguide.html&d=DwICAg&c=sJ6xIWYx-zLMB3EPkvcnVg&r=9PEhQh2kVeAsRzsn7AkP-g&m=eyJm06tVDfKvtMDgz6oIWM-WVdoW3Szzb5G6rq0cCO_cB6ljj2x80E4oRkt3Vgba&s=L9VXAAYzIzrG2h17hBO-Qfg_EoS2mRQbjs3sRESp62Q&e=
and provide commented, minimal, self-contained, reproducible code.



More information about the R-help mailing list