Home » How to Fix in R: missing values are not allowed in subscripted assignments

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

by Erma Khan

One error message you may encounter when using R is:

Error in `[

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 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 

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 %in% operator when performing the assignment:

#assign column B a value of 10 where A is equal to 5
df[df$A %in% 5,]$B #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()

Another way to avoid this error is to use the is.na() function when performing the assignment:

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

Additional Resources

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

How to Fix in R: Arguments imply differing number of rows
How to Fix in R: error in select unused arguments
How to Fix in R: replacement has length zero

Related Posts