replace NA with 0 and all other values/text as 1

拈花ヽ惹草 提交于 2021-02-17 06:39:35

问题


airquality

    Ozone Solar.R Wind Temp Month Day
1      41     190  7.4   67     5   1
2      36     118  8.0   72     5   2
3      12     149 12.6   74     5   3
4      18     313 11.5   62     5   4
5      NA      NA 14.3   56     5   5
6      28      NA 14.9   66     5   6
7      23     299  8.6   65     5   7
8      19      99 13.8   59     5   8
9       8      19 20.1   61     5   9

Hi there,

How do I replace values in Ozone to be binary? If NA then 0 and if a value then 1.

Thanks H


回答1:


Assuming your dataframe is called airquality

airquality$Ozone <- ifelse(is.na(airquality$Ozone), 0, 1) 



回答2:


airquality$Ozone <- as.integer(!is.na(airquality$Ozone))



回答3:


Alternatively

airquality$Ozone[!is.na(airquality$Ozone)] <- 1L
airquality$Ozone[is.na(airquality$Ozone)] <- 0L


来源:https://stackoverflow.com/questions/61388393/replace-na-with-0-and-all-other-values-text-as-1

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!