R Error missing values not allowed in subscripted assignments (2 Examples)

In this R tutorial you’ll learn how to deal with the “Error in X : missing values are not allowed in subscripted assignments of data frames”.

Creation of Example Data

my_df <- data.frame(var1 = c(NA, "a", NA, "a", "b"),         # Create example data
                    var2 = 11:15)
my_df                                                        # Print example data
#   var1 var2
# 1 <NA>   11
# 2    a   12
# 3 <NA>   13
# 4    a   14
# 5    b   15

Example 1: Reproduce the Error – missing values are not allowed in subscripted assignments of data frames

my_df[my_df$var1 == "a", ]$var2 <- 100                       # Try to replace values
# Error in `[<-.data.frame`(`*tmp*`, my_df$var1 == "a", , value = list(var1 = c(NA,  : 
#   missing values are not allowed in subscripted assignments of data frames

Example 2: Fix the Error – missing values are not allowed in subscripted assignments of data frames

my_df[!is.na(my_df$var1) & my_df$var1 == "a", ]$var2 <- 100  # Properly replace values
my_df                                                        # Print updated data
#   var1 var2
# 1 <NA>   11
# 2    a  100
# 3 <NA>   13
# 4    a  100
# 5    b   15

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