Home » How to Impute Missing Values in R (With Examples)

How to Impute Missing Values in R (With Examples)

by Erma Khan

Often you may want to replace missing values in the columns of a data frame in R with the mean or the median of that particular column.

To replace the missing values in a single column, you can use the following syntax:

df$col[is.na(df$col)] na.rm=TRUE)

And to replace the missing values in multiple columns, you can use the following syntax:

for(i in 1:ncol(df)) {
  df[ , i][is.na(df[ , i])] na.rm=TRUE)
}

This tutorial explains exactly how to use these functions in practice.

Example 1: Replace Missing Values with Column Means

The following code shows how to replace the missing values in the first column of a data frame with the mean value of the first column:

#create data frame
df #replace missing values in first column with mean of first column
df$var1[is.na(df$var1)] na.rm=TRUE)

#view data frame with missing values replaced
df

      var1 var2 var3 var4
1 1.000000    7    3    1
2 3.333333    7    3    1
3 3.333333    8    6    2
4 4.000000    3    6    8
5 5.000000    2    8    9

The mean value in the first column was 3.333, so the missing values in the first column were replaced with 3.333.

The following code shows how to replace the missing values in each column with the mean of its own column:

#create data frame
df #replace missing values in each column with column means
for(i in 1:ncol(df)) {
  df[ , i][is.na(df[ , i])] na.rm=TRUE)
}

#view data frame with missing values replaced
df

      var1 var2     var3 var4
1 1.000000    7 5.666667    1
2 3.333333    7 3.000000    1
3 3.333333    8 6.000000    2
4 4.000000    6 5.666667    8
5 5.000000    2 8.000000    9

Example 2: Replace Missing Values with Column Medians

The following code shows how to replace the missing values in the first column of a data frame with the median value of the first column:

#create data frame
df #replace missing values in first column with median of first column
df$var1[is.na(df$var1)] na.rm=TRUE)

#view data frame with missing values replaced
df

  var1 var2 var3 var4
1    1    7   NA    1
2    4    7    3    1
3    4    8    6    2
4    4   NA   NA    8
5    5    2    8    9

The median value in the first column was 4, so the missing values in the first column were replaced with 4.

The following code shows how to replace the missing values in each column with the median of its own column:

#create data frame
df #replace missing values in each column with column medians
for(i in 1:ncol(df)) {
  df[ , i][is.na(df[ , i])] na.rm=TRUE)
}

#view data frame with missing values replaced
df

  var1 var2 var3 var4
1    1    7    6    1
2    4    7    3    1
3    4    8    6    2
4    4    7    6    8
5    5    2    8    9

Additional Resources

How to Loop Through Column Names in R
How to Calculate the Mean of Multiple Columns in R
How to Sum Specific Columns in R

Related Posts