R Error: Subscript Out of Bounds (Example)


In this R tutorial you’ll learn how to fix the error message subscript out of bounds.

The article is structured as follows:

Let’s start right away.


Creating Example Data

First, we’ll have to create some example data:

my_mat <- matrix(1:20, ncol = 5)    # Create example matrix
my_mat                              # Print example matrix
#      [,1] [,2] [,3] [,4] [,5]
# [1,]    1    5    9   13   17
# [2,]    2    6   10   14   18
# [3,]    3    7   11   15   19
# [4,]    4    8   12   16   20

Have a look at the previous output of the RStudio console. It shows that our example data is a numeric matrix consisting of four rows and five columns.


Example: Reproducing & Solving the Error: Subscript Out of Bounds

This Example shows the reason why the error message “subscript out of bounds” occurs.

Let’s assume that we want to extract certain rows or columns of our matrix. Then we could apply the following R code:

my_mat[3, ]                         # Printing third row of matrix
# [1]  3  7 11 15 19

As you can see in the previous output, we extracted the third row of our data set.

Now, let’s assume that we want to extract a row that doesn’t exist in our data (i.e. the 10th row):

my_mat[10, ]                        # Trying to print tenth row of matrix
# Error in my_mat[10, ] : subscript out of bounds

Then the R programming language returns the error message “subscript out of bounds”.

In other words: If you are receiving the error message “subscript out of bounds” you should check whether you are trying to use a data element that does not exist in your data.


Video, Further Resources & Summary

Do you need more info on the R codes of this tutorial? Then you could have a look at the following video which I have published on my YouTube channel. In the video, I show the R code of this tutorial:



In addition, you might want to have a look at the other articles on my homepage.


On this page you learned how to solve the error subscript out of bounds in R programming. In case you have additional questions, let me know in the comments below. Furthermore, please subscribe to my email newsletter in order to receive updates on the newest articles.


Subscribe to the Statistics Globe Newsletter

Get regular updates on the latest tutorials, offers & news at Statistics Globe.
I hate spam & you may opt out anytime: Privacy Policy.

27 Comments. Leave new

  • Goitom Kelem
    March 15, 2022 4:30 pm

    The dimension of the data is 2592 by 2 and I do like to create area weighted value but it gives me an error subscript out of bounds. Kindly please help me to solve the problem, thank you very much.
    [1] 2592 2
    for(j in 3:1647) {for (i in 1:2592) {if(temp[i,j]> -290.0) {areaw[i,j]=veca[i]} }}
    Error in temp[i, j] : subscript out of bounds

  • Goitom Kelem
    March 16, 2022 7:47 am

    Dear Joachim,
    Thank you very much for your fast replay, the objective is to make a time series plot for a specific region by sub-setting data from a large domain. The data has missing value with -999.9 , the missing value has to be replaced by zero
    #36-by-72 boxes and Jan1880-Jan2016=1633 months + lat and lon
    areaw=matrix(0,nrow=2592,ncol = 1647)
    #[1] 2592 1647
    #create an area-weight matrix equal to cosine box with data and zero for missing
    #[1] 2592 2
    for(j in 3:1647) {for (i in 1:2592) {if(temp[i,j]> -290.0) {areaw[i,j]=veca[i]} }}
    Error in temp[i, j] : subscript out of bounds

    #—- After the error is fixed the next step will be this below script
    #area-weight data matrixs first two columns as lat-lon
    #create monthly global average vector for 1645 months
    #Jan 1880- Jan 2017
    #area-weight data matrixs first two columns as lat-lon
    #create monthly global average vector for 1645 months
    #Jan 1880- Jan 2017
    plot(timemo,avev,type=”l”, cex.lab=1.4,
    xlab=”Year”, ylab=”Temperature anomaly [oC]”,
    main=”Area-weighted global average of monthly SAT anomalies: Jan 1880-Jan 2017″)
    abline(lm(avev ~ timemo),col=”blue”,lwd=2)
    text(1930,0.7, “Linear trend: 0.69 [oC] per century”,
    cex=1.4, col=”blue”)

    Again thank you very much for your kindly help

    • If you want to replace the missing values (i.e. -999.9) by 0, you may simply use the following code:

      temp[temp == -999.9] <- 0

      I do not understand what you are trying to do with this part of the code: for(j in 3:1647) {for (i in 1:2592) {if(temp[i,j]> -290.0) {areaw[i,j]=veca[i]} }}

      However, maybe the missing value replacement above already solves your problem?


      • Goitom Kelem
        March 16, 2022 1:32 pm

        Dear Joachim,

        Thank you very much for your time, the missing data is replaced to zero based on your code. I will late know the remained part and I will come again with a clear figure and question, dear.

        Blessed day
        Best Regards
        Goitom Kelem

  • Hello!

    I am getting this error message in r: “Error in opts[[x]] : subscript out of bounds” when I run One-Way ANOVAs with different variations of the DV and IVs. I used to run the analysis with no problem a few days ago and now none of the one-way ANOVAs I created is running. Not sure if I am missing a package or if low memory storage in r has to do anything with this. Here is the code I am using to run the analysis:


    jmv::ANOVA(data = studentsurvey,
    dep = ‘SATISFAC_LIKELAB’, #dependent variable
    factors = c(‘Grade’), #iv
    effectSize = ‘partEta’,
    postHoc = c(‘Grade’),
    postHocCorr = ‘tukey’,
    postHocES = ‘d’,
    emMeans = list(‘Grade’),
    emmTables = TRUE,
    emmPlotError = ‘ci’)

    • Hey Amanda,

      Could you please illustrate the structure of your data? What is returned when you execute the following code?



  • Michael Tetteh
    July 20, 2022 7:12 pm

    I tried to run the summary of my SBM Efficiency results but I kept having this error code

    Error in `[<-`(`*tmp*`, urefnames, refnames, value = round(lmbd[urefnames, :
    subscript out of bounds

    All the results showed up in the console though. Please what could be the problem? Any solutions?


    • Hey Michael,

      Could you please share your code?


      • Michael Tetteh
        July 24, 2022 2:30 am

        >##create a “read_data” object

        >SBMAgric=Main_InputOutput_Data data_exampleSBMAgricResultsefficiencies(SBMAgricResults)

        > slacks(SBMAgricResults)


        This reply surpasses the earlier one.

        Kindly let me know if this meet your request.

        Thank you.

      • Michael Tetteh
        July 24, 2022 10:53 pm

        Hello Joachim,

        I’ve been able to resolve the problem (I reduced the length of the names of my DMUs to fit the boundary).


  • Dear Joachim
    I am trying to install Runway package in R ( Blue sky version)
    I get this error message
    Can you advice?

    Enter one or more numbers, or an empty line to skip updates:
    Error: Failed to install ‘runway’ from GitHub:
    subscript out of bounds
    In addition: Warning message:
    In memory.limit(4095) : cannot decrease memory limit: ignored
    Error:Error: Failed to install ‘runway’ from GitHub:
    subscript out of bounds

    • Hi Thambu,

      I apologize for the delayed reply. I was on a long vacation, so unfortunately I wasn’t able to get back to you earlier. Do you still need help with your syntax?


  • Hi Joachim,

    I am getting error,

    Error in y_scales[[2]] : subscript out of bounds

    Here is the code


    overall$Treatments<-factor(overall$Treatments,levels=c("pH (lnRR)","C/N ratio", "∆SOC (%)","∆TN (%)"))

    geom_bar(stat = "identity")+
    facet_zoom(ylim = c(-14.5, 0))+
    geom_errorbar(mapping = aes(ymin=min,ymax=max),width=0,position = position_dodge(width = 25))+
    geom_hline(yintercept=0,linetype="dashed", color = "red",size=0.5)+
    geom_text(aes(label=N,hjust=0.5, vjust=-1.5),size=3.15)+
    theme(axis.title.y = element_blank(),axis.title.x = element_blank())+
    theme(axis.text = element_text(size = 11,angle = 0),plot.title = element_text(size = rel(0.75)))+
    theme(aspect.ratio = 1.75/4)+
    theme(legend.position = "none")+
    theme(panel.grid.major = element_blank(), panel.grid.minor = element_blank(),
    panel.background = element_blank())

    • Hello Shahid,

      It is hard to comment on this while not seeing your dataset. But it is probably about the incompatibility between the range of your y data and the values you have assigned for ylim, y-intercept, etc.


  • Hello,
    Please I am running a script, it has 28 column and I want to subset and plot a forest plot using the code
    p1 <- forest(M[,c(1, 23:28)]
    est = M$est,
    lower = M$low,
    upper = M$hi,
    sizes = M$se,
    ci_column = 6,
    ref_line = 1,
    arrow_lab = c("Placebo Better", "Treatment Better"),
    xlim = c(0, 2),
    ticks_at = c(0.4, 0.9, 1.75))

    but I received an error that "Error in names[[i]] : subscript out of bounds"
    Please can you help me to fix this error. Thank you

    • Hello Stephany,

      It looks like the dimensions of the names array (I don’t know what corresponds to it in the forest function) do not match your dataset dimensions. But I can not tell further. You should double-check the inputs you provide to the function. Alternatively, you can post your question on our Facebook discussion group. Maybe someone has already dealt with this issue in the context of forest plots.


  • Santos Barrera
    May 24, 2023 11:39 pm

    Error in L_star[, i] : subscript out of bounds

  • Hi,
    I have 2columns and 200rows, monthly data. When running TVPVAR in R, it gives me this error: Error in rva1 [i, , drop=drop., …] : subscript out of bounds. Please help me if you possibly can. It’s bad on the nerve. I set nlag=1, nfore=10, window.size=200.

    • Hello Tom,

      It is hard to make a judgment knowing so little about your dataset. However, I can provide some general troubleshooting tips that might help you:

      Data Dimensions: Ensure that the data you’re feeding to the function actually has 200 rows and 2 columns.

      dim(your_data) # should return 200 2

      Missing Values: Check if there are any missing values in your data. Missing values can sometimes cause unexpected behavior.


      Check Arguments:

      Ensure nlag=1 is appropriate for your data. This means that the TVP-VAR model will use one lag of the endogenous variables as regressors.
      Ensure nfore=10 is appropriate. This determines how many steps ahead you want to forecast.
      window.size=200 seems problematic. The window size is the size of the rolling window used for estimation. Setting it equal to the number of observations (200 in your case) means you’re trying to use all the data points in the estimation window, leaving none for out-of-sample validation. Try reducing the window size. A typical approach would be to set it to something like 0.8 times the sample size if you want an 80-20 train-test split, but the specific choice depends on your goals.


  • Dear Consu,
    I appreciate you assigning time. Your advice was very helpful. I found out that the dim is 200 2 before converting my data to zoo. But, after converting, the dim shows 1 2 !!! I don’t know why such an issue happens after converting! Anyway, i learned where the issue is now due to your guidance. Thank you again. I will be grateful if you possibly let me know about the dim issue after converting. Do you think it relates to zoo package?

  • Hello Joachim. Good afternoon.
    My problem is that I have an app in Shiny that is working perfectly. When I try to use the bs4Dash package it gives the error.
    Error in subItems[[i]] : subscript out of bounds

    Can you help?

    • Hello Jose,

      When integrating bs4Dash with a Shiny app, this error could be caused by a variety of issues. However, common problems that could cause such an error include:

      Incorrect structure in UI elements: The UI elements provided by bs4Dash might require a different structure or arguments than the regular Shiny UI elements. Make sure you’re using them correctly.

      Menu Items: The error could be related to the sidebar menu items. For instance, if you’ve used bs4Dash::bs4SidebarMenu or bs4Dash::bs4TabItems, ensure that the structure of items and sub-items is correctly formatted.

      Mismatched Tabs and Content: If you’re using tabbed content with bs4Dash, ensure that each tab item in the UI corresponds to a tab content on the server side.



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.