How to Solve the Error – Subscript Out of Bounds in R (Example Code)

On this page, I’ll illustrate how to fix the error subscript out of bounds in the R programming language.

Introducing Exemplifying Data

example_matrix <- matrix(1:100,    # Creating & printing example matrix
                         nrow = 10)
example_matrix
#       [,1] [,2] [,3] [,4] [,5] [,6] [,7] [,8] [,9] [,10]
# [1,]     1   11   21   31   41   51   61   71   81    91
# [2,]     2   12   22   32   42   52   62   72   82    92
# [3,]     3   13   23   33   43   53   63   73   83    93
# [4,]     4   14   24   34   44   54   64   74   84    94
# [5,]     5   15   25   35   45   55   65   75   85    95
# [6,]     6   16   26   36   46   56   66   76   86    96
# [7,]     7   17   27   37   47   57   67   77   87    97
# [8,]     8   18   28   38   48   58   68   78   88    98
# [9,]     9   19   29   39   49   59   69   79   89    99
# [10,]   10   20   30   40   50   60   70   80   90   100

Example: Fix the Error Message: Subscript Out of Bounds

This works, since the matrix has a fifth column.

example_matrix[ , 5]               # Print only one column
#  [1] 41 42 43 44 45 46 47 48 49 50

This does not work, because the matrix does not have a 20th column.

example_matrix[ , 20]              # Try to return non-existing column
# Error in example_matrix[, 20] : subscript out of bounds

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