# How to replace NA with 0 and other values to 1 in an R data frame column?

Sometimes we want to convert a column of an R data frame to binary column using 0 and 1, it is especially done in situations where we have some NAs in the column of the data frame and the other values can be converted to 1 due to some characteristics. To replace NA with 0 and other values to 1, we can use ifelse function.

## Example1

Live Demo

Consider the below data frame −

x1<−1:20
x2<−sample(c(NA,rnorm(5)),20,replace=TRUE)
df1<−data.frame(x1,x2)
df1

## Output

x1 x2
1 1 1.6562106
2 2 NA
3 3 2.2323438
4 4 2.2323438
5 5 1.2038679
6 6 2.2323438
7 7 NA
8 8 1.6562106
9 9 NA
10 10 1.2038679
11 11 −0.6898052
12 12 2.2323438
13 13 2.2323438
14 14 1.6562106
15 15 NA
16 16 1.2038679
17 17 NA
18 18 −0.6898052
19 19 2.2323438
20 20 2.2323438

Replacing NAs with 0 and other values to 1 in column x2 −

## Example

df1$x2<−ifelse(is.na(df1$x2),0,1)
df1

## Output

x1 x2
1 1 1
2 2 0
3 3 1
4 4 1
5 5 1
6 6 1
7 7 0
8 8 1
9 9 0
10 10 1
11 11 1
12 12 1
13 13 1
14 14 1
15 15 0
16 16 1
17 17 0
18 18 1
19 19 1
20 20 1

## Example2

Live Demo

y1<−LETTERS[1:20]
y2<−sample(c(NA,rpois(5,2)),20,replace=TRUE)
df2<−data.frame(y1,y2)
df2

## Output

y1 y2
1 A 2
2 B 5
3 C NA
4 D 3
5 E 1
6 F NA
7 G 1
8 H 3
9 I 5
10 J 5
11 K NA
12 L NA
13 M 2
14 N 5
15 O 3
16 P 2
17 Q 2
18 R 1
19 S 2
20 T NA

Replacing NAs with 0 and other values to 1 in column y2 −

## Example

df2$y2<−ifelse(is.na(df2$y2),0,1)
df2

## Output

y1 y2
1 A 1
2 B 1
3 C 0
4 D 1
5 E 1
6 F 0
7 G 1
8 H 1
9 I 1
10 J 1
11 K 0
12 L 0
13 M 1
14 N 1
15 O 1
16 P 1
17 Q 1
18 R 1
19 S 1
20 T 0