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

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
Updated on: 2026-03-11T22:50:55+05:30

887 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements