Home > Software design >  Change the values of a column in a specific condition in R
Change the values of a column in a specific condition in R

Time:10-03

Here, I made 2 columns y and delta

y=matrix(c(1,1,1,0,0,0,1,0),nrow=8)
delta=matrix(c(1,0,0,0,1,0,0,0),nrow=8)

What I want to do now is make new y. I want to treat delta as an indicator for missing values of y. If delta is 1, I will treat y as observed. If delta is 0, I will treat y as missing. So the expected output for y should be

y=matrix(c(1,NA,NA,NA,0,NA,NA,NA),nrow=8)

CodePudding user response:

We could use convert the 0 elements in delta to NA and multiply by y

(NA^!delta) * y

-output

     [,1]
[1,]    1
[2,]   NA
[3,]   NA
[4,]   NA
[5,]    0
[6,]   NA
[7,]   NA
[8,]   NA
  • Related