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

纵饮孤独 提交于 2019-12-22 05:54:23

问题


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!


回答1:


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.



来源:https://stackoverflow.com/questions/11831786/error-in-tmpj-subscript-out-of-bounds

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!