简体   繁体   中英

R: How to recode values of a variable to NA for cases where another variable has a value of NA

I'm cleaning a dataset and I need to recode a variable, DebtRatio, to have the value NA when MonthlyIncome has a value of NA. By default this is not true and thus the values which have NA are giving crazy values for DebtRatio (naturally). However these cases have a variety of other interesting information so I dont wish to remove them completely. Simply recode the values of these cases to NA.

However when I run my script, it doesnt seem to behave the way I want. I dont receive an error in the terminal but the values dont change at all.

credit_train_18$DebtRatio[credit_train_18$MonthlyIncome == NA] <- NA

This works when recoding my categorical variables so I'm not sure why it fails in this particular case.

I would really appreciate a solution to this problem

You should use is.na() rather than checking for equality.

credit_train_18$DebtRatio[is.na(credit_train_18$MonthlyIncome)] <- NA

Your approach is problematic because NA == NA returns NA rather than TRUE.

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