Intellipaat Back

Explore Courses Blog Tutorials Interview Questions
0 votes
2 views
in R Programming by (7.3k points)

I have a data frame with some numeric columns. Some row has a 0 value which should be considered as null in statistical analysis. What is the fastest way to replace all the 0 value to NULL in R?

1 Answer

0 votes
by

To replace all 0 values to NA in the data frame you can use the following syntax:

set.seed(123)

df <- data.frame(x = sample(0:2, 5, TRUE), y = sample(0:1, 5, TRUE))

df

x y

1 2 1

2 2 1

3 2 1

4 1 0

5 2 0

df[df == 0] <- NA

df

df

  x y

1 2 1

2 2 1

3 2 1

4 1 0

5 2 0

You can also use the na_if function from the dplyr package, as follows:

library('dplyr')

 na_if(df, 0)

  x  y

1 2  1

2 2  1

3 2  1

4 1 NA

5 2 NA

Related questions

31k questions

32.8k answers

501 comments

693 users

Browse Categories

...