How to convert empty values to NA in an R data frame?

When our data has empty values then it is difficult to perform the analysis, we might to convert those empty values to NA so that we can understand the number of values that are not available. This can be done by using single square brackets.

Example

Consider the below data frame that has some empty values −

> x1<-c(rep(c(1,2,3),times=5),"","","",2,1)
> x2<-rep(c(2,4,"",4,""),each=4)
> x3<-rep(c(5,4,2,""),times=c(2,5,3,10))
> df<-data.frame(x1,x2,x3)
> df
x1 x2 x3
1 1 2 5
2 2 2 5
3 3 2 4
4 1 2 4
5 2 4 4
6 3 4 4
7 1 4 4
8 2 4 2
9 3 2
10 1 2
11 2
12 3
13 1 4
14 2 4
15 3 4
16 4
17
18
19 2
20 1

Converting empty values to NA −

> df[df == ""]<-NA
> df
x1 x2 x3
1 1 2 5
2 2 2 5
3 3 2 4
4 1 2 4
5 2 4 4
6 3 4 4
7 1 4 4
8 2 4 2
9 3 <NA> 2
10 1 <NA> 2
11 2 <NA> <NA>
12 3 <NA> <NA>
13 1 4 <NA>
14 2 4 <NA>
15 3 4 <NA>
16 <NA> 4 <NA>
17 <NA> <NA> <NA>
18 <NA> <NA> <NA>
19 2 <NA> <NA>
20 1 <NA> <NA>