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


To convert NaN values to NA, we would need to detect the NaN values in the data frame and the set them to NA. For example, if we have a data frame called df that contains a column x which has some NaN values then we can convert those NaN to NA by using the command df$x[is.nan(df$x)]<-NA

Example1

Consider the below data frame −

Live Demo

> x1<-sample(c(1,NaN),20,replace=TRUE)
> x2<-rnorm(20)
> df1<-data.frame(x1,x2)
> df1

Output

x1 x2
1 NaN -0.44923302
2 NaN -0.12670027
3 1 0.59120380
4 1 -0.18782341
5 NaN -0.28730385
6 1 0.57412261
7 NaN -0.33620181
8 1 1.37168545
9 NaN -2.24121448
10 NaN 1.05990104
11 1 1.95544957
12 NaN -2.19544854
13 1 -0.94131203
14 1 -0.37307028
15 NaN 1.21659101
16 1 -0.03788952
17 1 -0.16122552
18 1 0.90254474
19 1 -0.73196835
20 NaN -0.28462669

Converting NaN in x1 to NA −

> df1$x1[is.nan(df1$x1)]<-NA
> df1

Output

x1 x2
1 NA -0.44923302
2 NA -0.12670027
3 1 0.59120380
4 1 -0.18782341
5 NA -0.28730385
6 1 0.57412261
7 NA -0.33620181
8 1 1.37168545
9 NA -2.24121448
10 NA 1.05990104
11 1 1.95544957
12 NA -2.19544854
13 1 -0.94131203
14 1 -0.37307028
15 NA 1.21659101
16 1 -0.03788952
17 1 -0.16122552
18 1 0.90254474
19 1 -0.73196835
20 NA -0.28462669

Example2

Live Demo

> y1<-sample(c(5,NaN),20,replace=TRUE)
> y2<-rpois(20,5)
> df2<-data.frame(y1,y2)
> df2

Output

y1 y2
1 NaN 7
2 NaN 5
3 NaN 3
4 5 4
5 5 4
6 5 4
7 5 4
8 NaN 4
9 5 5
10 NaN 5
11 5 5
12 5 2
13 5 9
14 5 3
15 NaN 6
16 NaN 8
17 5 5
18 5 7
19 NaN 4
20 NaN 8

Converting NaN in y1 to NA −

> df2$y1[is.nan(df2$y1)]<-NA
> df2

Output

y1 y2
1 NA 7
2 NA 5
3 NA 3
4 5 4
5 5 4
6 5 4
7 5 4
8 NA 4
9 5 5
10 NA 5
11 5 5
12 5 2
13 5 9
14 5 3
15 NA 6
16 NA 8
17 5 5
18 5 7
19 NA 4
20 NA 8

Updated on: 04-Mar-2021

443 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements