简体   繁体   中英

Change the values of a column in a specific condition in R

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)

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM