Hi, I am trying to index the rows of a model matrix where, due to missing values in the dataset used for the regression, the row numbers sometimes "jump" like this:> X[17:19,](Intercept) PCINIFM 17 1 36.76471 19 1 13.23529 20 1 32.35294 So, the problem is if I select for example X[20, ], I actually get the 21th observation. I've tried to work around this problem by using X[as.character(20) , ]. Thus I actually get what I want. However, I need to access sequences of rows, but if there is some missing row, this doesn't work:> X[as.character(17:19),]Error: subscript out of bounds Is there a way to make R handle this more gracefully, so that, in this case, it would just return the rows 17 and 19 without complaining? I apologize in advance for this dumb question of the beginner who I am and for which I didn't find a solution in the documentation! Thanks in advance, Nils
Ferdinand Alimadhi
2005-Dec-11 00:39 UTC
[R] Problem with indexing (subscript out of bounds)
There are two ways to index the matrices, using indexes of the row and columns or using names of rows and columns. In your example, it seems that you need to index your matrix by row names. X[rownames(X) %in% 17:19, ] could give the result you want. Nils Trebing wrote:>Hi, > >I am trying to index the rows of a model matrix where, due to missing >values in the dataset used for the regression, the row numbers sometimes >"jump" like this: > > > >>X[17:19,] >> >> > (Intercept) PCINIFM >17 1 36.76471 >19 1 13.23529 >20 1 32.35294 > >So, the problem is if I select for example X[20, ], I actually get the >21th observation. I've tried to work around this problem by using >X[as.character(20) , ]. Thus I actually get what I want. However, I need >to access sequences of rows, but if there is some missing row, this >doesn't work: > > > >>X[as.character(17:19),] >> >> >Error: subscript out of bounds > >Is there a way to make R handle this more gracefully, so that, in this >case, it would just return the rows 17 and 19 without complaining? > >I apologize in advance for this dumb question of the beginner who I am >and for which I didn't find a solution in the documentation! > >Thanks in advance, >Nils > >______________________________________________ >R-help@stat.math.ethz.ch mailing list >https://stat.ethz.ch/mailman/listinfo/r-help >PLEASE do read the posting guide! http://www.R-project.org/posting-guide.html > >[[alternative HTML version deleted]]
Ferdinand Alimadhi wrote:> There are two ways to index the matrices, using indexes of the row and > columns or using names of rows and columns. > In your example, it seems that you need to index your matrix by row names. > > X[rownames(X) %in% 17:19, ] > > could give the result you want.Thanks a lot, this did the trick! Regards, Nils