R Error: incorrect number of subscripts on matrix (2 Examples)
This article illustrates how to handle the error message “incorrect number of subscripts on matrix” in the R programming language.
The content of the tutorial looks as follows:
If you want to know more about these topics, keep reading:
Creation of Example Data
The first step is to create some example data.
x <- 1:5 # Create example vector x # Print example vector #  1 2 3 4 5
The previous output of the RStudio console shows the structure of our example data: It’s a vector object ranging from the numerical values 1 to 5.
Example 1: Reproduce the Error – incorrect number of subscripts on matrix
In this example, I’ll show how to replicate the error message “incorrect number of subscripts on matrix” in the R programming language.
Let’s assume that we want to replace a certain index position of our vector. Then, we might try to use the following R code:
x[1, 3] <- 7 # Try to replace value # Error in x[1, 3] <- 7 : incorrect number of subscripts on matrix
Unfortunately, the RStudio console returns the error message “incorrect number of subscripts on matrix”.
The reason for this is that we have specified a two-dimensional subset of a one-dimensional vector (i.e. [1, 3]).
So how can we solve this problem in R?
Example 2: Fix the Error – incorrect number of subscripts on matrix
In this section, I’ll show how to replace values in a vector object properly to avoid the error “incorrect number of subscripts on matrix”.
For this, we have to specify only a single value (i.e. index position) within the square brackets behind our vector object:
x <- 7 # Properly replace value x # Print updated vector #  7 2 3 4 5
Have a look at the previous output: We have replaced the first value of our vector by the new value 7.
Video & Further Resources
Do you want to know more about errors in R? Then you may want to watch the following video of my YouTube channel. In the video, I illustrate the content of this article.
The YouTube video will be added soon.
In addition, you might have a look at the other articles on this homepage.
In summary: In this R tutorial you have learned how to debug the error “incorrect number of subscripts on matrix”. In case you have any further questions, don’t hesitate to let me know in the comments below.