How to remove rows from data frame in R that contains NaN?



The NaN values are referred to as the Not A Number in R. It is also called undefined or unrepresentable but it belongs to numeric data type for the values that are not numeric, especially in case of floating-point arithmetic. To remove rows from data frame in R that contains NaN, we can use the function na.omit.

Example1

 Live Demo

Consider the below data frame −

x1<−sample(c(NaN,5,10),20,replace=TRUE) x2<−sample(c(NaN,0,1),20,replace=TRUE) df1<−data.frame(x1,x2) df1

Output

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

Removing rows with NaN from df1 −

df1<−na.omit(df1) df1

Output

x1 x2 2 10 0 7 5 1 8 5 1 15 10 1 16 10 0 20 5 1

Example2

 Live Demo

y1<−sample(c(NaN,rnorm(5)),20,replace=TRUE) y2<−sample(c(NaN,rnorm(2)),20,replace=TRUE) df2<−data.frame(y1,y2) df2

Output

y1 y2 1 0.71997269 NaN 2 0.31324492 NaN 3 0.71997269 −0.1903841 4 1.23101131 −0.1903841 5 0.09512564 −0.1903841 6 0.71997269 0.3998648 7 −0.14221014 −0.1903841 8 0.09512564 NaN 9 NaN NaN 10 1.23101131 0.3998648 11 −0.14221014 0.3998648 12 1.23101131 NaN 13 NaN 0.3998648 14 0.71997269 NaN 15 0.09512564 NaN 16 0.31324492 NaN 17 NaN NaN 18 0.09512564 0.3998648 19 1.23101131 0.3998648 20 0.71997269 −0.1903841

Removing rows with NaN from df2 −

Example

df2<−na.omit(df2) df2

Output

y1 y2 3 0.71997269 −0.1903841 4 1.23101131 −0.1903841 5 0.09512564 −0.1903841 6 0.71997269 0.3998648 7 −0.14221014 −0.1903841 10 1.23101131 0.3998648 11 −0.14221014 0.3998648 18 0.09512564 0.3998648 19 1.23101131 0.3998648 20 0.71997269 −0.1903841
Updated on: 2021-02-09T11:57:56+05:30

15K+ Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements