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:
Please accept YouTube cookies to play this video. By accepting you will be accessing content from YouTube, a service provided by an external third party.
If you accept this notice, your choice will be saved and the page will refresh.
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.
21 Comments. Leave new
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.
dim(temp)
[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
Hey Goitom,
Could you explain what you want to do with this part of the code: for(j in 3:1647) ?
Regards,
Joachim
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)
dim(areaw)
#[1] 2592 1647
areaw[,1]=temp[,1]
areaw[,2]=temp[,2]
#create an area-weight matrix equal to cosine box with data and zero for missing
dim(temp)
#[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
tempw=areaw*temp
tempw[,1:2]=temp[,1:2]
#create monthly global average vector for 1645 months
#Jan 1880- Jan 2017
avev=colSums(tempw[,3:1647])/colSums(areaw[,3:1647])
#
#
#area-weight data matrixs first two columns as lat-lon
tempw=areaw*temp
tempw[,1:2]=temp[,1:2]
#create monthly global average vector for 1645 months
#Jan 1880- Jan 2017
avev=colSums(tempw[,3:1647])/colSums(areaw[,3:1647])
#
#
timemo=seq(1880,2017,length=1645)
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:
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?
Regards,
Joachim
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
Glad it was helpful! 🙂
Regards,
Joachim
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:
“`{r}
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?
Regards,
Joachim
Hello,
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?
Thanks,
Michael.
Hey Michael,
Could you please share your code?
Regards,
Joachim
>##create a “read_data” object
>SBMAgric=Main_InputOutput_Data data_exampleSBMAgricResultsefficiencies(SBMAgricResults)
> slacks(SBMAgricResults)
>summary(SBMAgricResults)
This reply surpasses the earlier one.
Kindly let me know if this meet your request.
Thank you.
Hello Joachim,
I’ve been able to resolve the problem (I reduced the length of the names of my DMUs to fit the boundary).
Thanks.
Glad you found a solution Michael! 🙂
Dear Joachim
I am trying to install Runway package in R ( Blue sky version)
I get this error message
Can you advice?
Grateful
Thambu
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?
Regards,
Joachim
Hi Joachim,
I am getting error,
Error in y_scales[[2]] : subscript out of bounds
Here is the code
library(ggplot2)
library(scales)
library(ggforce)
overall<-R_overall
overall$Treatments<-factor(overall$Treatments,levels=c("pH (lnRR)","C/N ratio", "∆SOC (%)","∆TN (%)"))
ggplot(overall,aes(Treatments,Values,color=Treatments))+
geom_bar(stat = "identity")+
geom_col()+
facet_zoom(ylim = c(-14.5, 0))+
coord_flip()+
theme_bw()+
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.
Regards,
Cansu
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.
Regards,
Cansu
Error in L_star[, i] : subscript out of bounds
Hello Santos,
Do you get this error while running your code? I didn’t get your question very well. If so, could you share your code please?
Regards,
Cansu