Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Converting NAs to 0 and non-NA's to 1s in R

Tags:

dataframe

r

na

I am having trouble converting a table of NAs and different values to 0 for NAs and 1s for the all the values.

Table looks like this:

x    y    z
NA   8    NA
2    NA   NA
9    9    8
...

I was able to convert the NAs to 0 using:

data[is.na(data)] <- 0

But I couldn't manage to convert the other values for all the columns at once.

like image 978
tmmmmmi Avatar asked Aug 31 '25 03:08

tmmmmmi


2 Answers

You can do this with a simple ifelse (one-liner):

data <- data.frame(ifelse(is.na(data),0,1))

Or even easier:

+!is.na(data)

Both will give you:

##   x y z
## 1 0 1 0
## 2 1 0 0
## 3 1 1 1

Data:

data <- structure(list(x = c(NA, 2L, 9L), y = c(8L, NA, 9L), z = c(NA,               
     NA, 8L)), .Names = c("x", "y", "z"), row.names = c(NA, 3L), class = "data.frame")
like image 61
M-- Avatar answered Sep 02 '25 15:09

M--


Following the same approach as you mentioned in your example:

# example data
df = data.frame(x = c(5,4,NA),
                y = c(NA,3,9))

df

#    x  y
# 1  5 NA
# 2  4  3
# 3 NA  9

df[!is.na(df)] = 1
df[is.na(df)] = 0

#   x y
# 1 1 0
# 2 1 1
# 3 0 1

First replace all non NA values with 1 and then (the remaining) NAs with 0. If you replace NAs first, then all your values will be non NA and you'll end up with a dataframe full of 1s.

like image 40
AntoniosK Avatar answered Sep 02 '25 16:09

AntoniosK