You can use the following methods to replace zero with NA values in R:
Method 1: Replace Zero with NA in All Columns
df[df == 0]
Method 2: Replace Zero with NA in One Column
df$col1[df$col1 == 0]
Method 3: Replace Zero with NA in Several Specific Columns
df[, c('col1', 'col2')][df[, c('col1', 'col2')] == 0]
The following examples show how to use each method in practice with the following data frame:
#create data frame df frame(player=c('A', 'B', 'C', 'D', 'E'), pts=c(17, 12, NA, 9, 25), rebs=c(3, 3, NA, NA, 8), blocks=c(1, 1, 2, 4, NA)) #view data frame df player pts rebs blocks 1 A 17 3 1 2 B 12 3 1 3 C NA NA 2 4 D 9 NA 4 5 E 25 8 NA
Example 1: Replace Zero with NA in All Columns
The following code shows how to replace zeros with NA values in all columns of a data frame:
#replace zero with NA in all columns df[df == 0] #view updated data frame df player pts rebs blocks 1 A 17 3 1 2 B 12 3 1 3 C NA NA 2 4 D 9 NA 4 5 E 25 8 NA
Notice that the zeros have been replaced with NA values in every column of the data frame.
Example 2: Replace Zero with NA in One Column
The following code shows how to replace zero with NA values in one column of a data frame:
#replace zero with NA in 'rebs' column only df$rebs[df$rebs == 0] #view data frame player pts rebs blocks 1 A 17 3 1 2 B 12 3 1 3 C 0 NA 2 4 D 9 NA 4 5 E 25 8 0
Notice that each zero has been replaced with NA in the ‘rebs’ column while all other columns have remained unchanged.
Example 3: Replace Zero with NA in Several Specific Columns
The following code shows how to replace zero with NA values in several specific columns of a data frame:
#replace zero with NA values in 'pts' and 'rebs' columns only df[, c('pts', 'rebs')][df[, c('pts', 'rebs')] == 0] #view data frame df player pts rebs blocks 1 A 17 3 1 2 B 12 3 1 3 C NA NA 2 4 D 9 NA 4 5 E 25 8 0
Notice that each zero has been replaced with NA in the ‘pts’ and ‘rebs’ columns while the ‘blocks’ column has remained unchanged.
Additional Resources
The following tutorials explain how to perform other common tasks in R:
How to Replace Blanks with NA in R
How to Replace NAs with Strings in R
How to Replace NA with Mean in R
How to Replace NA with Median in R