How to fix in R: missing values are not allowed in subscripted assignments

When dealing with missing values in R, it is important to remember that they cannot be assigned to a subscripted variable. To fix this issue, the missing values should be replaced with a valid value before making the assignment. This can be done by using the is.na() function to identify the missing values and then using the replace() function to replace them with a valid value.


One error message you may encounter when using R is:

Error in `[<-.data.frame`(`*tmp*`, df$A == 5, , value = list(A = c(NA,  : 
  missing values are not allowed in subscripted assignments of data frames

This error usually occurs when you attempt to assign values in one column using values from another column, but there happen to be NA values present.

The following example shows how to resolve this error in practice.

How to Reproduce the Error

Suppose we create the following data frame in R:

#create data frame
df <- data.frame(A=c(3, 4, 4, NA, 5, 8, 5, 9),
                 B=c(12, 13, 7, 7, 12, 11, 15, 7))

#view data frame
df

   A  B
1  3 12
2  4 13
3  4  7
4 NA  7
5  5 12
6  8 11
7  5 15
8  9  7

Now suppose we attempt to assign a value of 10 to each row in column B where the corresponding value in column A is equal to 5:

#attempt to assign column B a value of 10 where A is equal to 5
df[df$A == 5, ]$B <- 10

Error in `[<-.data.frame`(`*tmp*`, df$A == 5, , value = list(A = c(NA,  : 
  missing values are not allowed in subscripted assignments of data frames

We receive an error because there are NA values in column A and we’re explicitly told in the error message that missing values are not allowed in subscripted assignments of data frames.

How to Avoid the Error

There are two ways to avoid this error.

1. Use %in% Operator

One way to avoid this error is to use the operator when performing the assignment:

#assign column B a value of 10 where A is equal to 5
df[df$A %in% 5,]$B <- 10

#view updated data frame
df

   A  B
1  3 12
2  4 13
3  4  7
4 NA  7
5  5 10
6  8 11
7  5 10
8  9  7

Notice that a value of 10 has been assigned to each row in column B where the corresponding value in column A is equal to 5 and we don’t receive any error.

2. Use is.na()

#assign column B a value of 10 where A is equal to 5
df[!is.na(df$A) & df$A == 5, ]$B <- 10

#view updated data frame
df

   A  B
1  3 12
2  4 13
3  4  7
4 NA  7
5  5 10
6  8 11
7  5 10
8  9  7

Once again we’re able to assign a value of 10 to each row in column B where the corresponding value in column A is equal to 5 and we don’t receive any error.

The following tutorials explain how to fix other common errors in R:

x