Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Error in *tmp*[[j]] : subscript out of bounds

Tags:

r

subscript

Apologies for long post! I'm new to R and have been working hard to improve my command of the language. I stumbled across this interesting project on modelling football results: http://www1.maths.leeds.ac.uk/~voss/projects/2010-sports/JamesGardner.pdf

I keep running into problems when I run the code to Simulate a Full Season (first mentioned page 36, appendix page 59):

Games <- function(parameters) 

{
teams <- rownames(parameters)
P <- parameters$teams
home <- parameters$home
n <- length(teams)
C <- data.frame()
row <- 1
for (i in 1:n) {
  for (j in 1:n) {
    if (i != j) {
C[row,1] <- teams[i]
C[row,2] <- teams[j]
C[row,3] <- rpois(1, exp(P[i,]$Attack - P[j,]$Defence + home))
C[row,4] <- rpois(1, exp(P[j,]$Attack - P[i,]$Defence))
row <- row + 1
    }
  }
}
return(C)
}

Games(TeamParameters)

The response I get is

Error in `*tmp*`[[j]] : subscript out of bounds 

When I attempt a traceback(), this is what I get:

3: `[<-.data.frame`(`*tmp*`, row, 1, value = NULL) at #11

2: `[<-`(`*tmp*`, row, 1, value = NULL) at #11

1: Games(TeamParameters)

I don't really understand what the error means and I would appreciate any help. Once again, apologies for the long post but I'm really interested in this project and would love to learn what the problem is!

like image 590
Clatty Cake Avatar asked Oct 08 '22 00:10

Clatty Cake


1 Answers

The data.frame objects are not extendable by row with the [<-.data.frame operation. (You would need to use rbind.) You should create an object that has sufficient space, either a pre-dimensioned matrix or data.frame. If "C" is an object of 0 rows, then trying to assign to row one will fail. There is a function named "C", so you might want to make its name something more distinct. It also seems likely that there are more efficient methods than the double loop but you haven't describe the parameter object very well.

You may notice that the Appendix of that paper you cited shows how to pre-dimension a dataframe:

teams <- sort(unique(c(games[,1], games[,2])), decreasing = FALSE) 
T <- data.frame(Team=teams,  ... )

... and the games-object was assumed to already have the proper number of rows and the results of computations were assigning new column values. The $<- operation will succeed if there is no current value for that referenced column.

like image 149
IRTFM Avatar answered Oct 12 '22 20:10

IRTFM