Exchange Missing Values in One Column by Another in R (Example Code)

In this R tutorial you’ll learn how to exchange NA values by another variable.

Creation of Example Data

data(iris)                                                                                             # Example data
iris_NA <- iris[1:6, c(1, 2)]
iris_NA$Sepal.Length[c(1, 3, 5)] <- NA
iris_NA
#   Sepal.Length Sepal.Width
# 1           NA         3.5
# 2          4.9         3.0
# 3           NA         3.2
# 4          4.6         3.1
# 5           NA         3.6
# 6          5.4         3.9

Example: Substituting NA Values in Particular Column by Adjacent Volumn

iris_NA$Sepal.Length[is.na(iris_NA$Sepal.Length)] <- iris_NA$Sepal.Width[is.na(iris_NA$Sepal.Length)]  # Exchange NAs
iris_NA                                                                                                # Display data
#   Sepal.Length Sepal.Width
# 1          3.5         3.5
# 2          4.9         3.0
# 3          3.2         3.2
# 4          4.6         3.1
# 5          3.6         3.6
# 6          5.4         3.9

Related Tutorials & Further Resources

Below, you can find some additional resources that are similar to the topic of this page:

Leave a Reply

Your email address will not be published. Required fields are marked *

Fill out this field
Fill out this field
Please enter a valid email address.
You need to agree with the terms to proceed

Menu
Top