Elegant indexing up to end of vector/matrix

前端 未结 3 1099
情歌与酒
情歌与酒 2020-12-08 01:45

Is it possible in R to say - I want all indices from position i to the end of vector/matrix? Say I want a submatrix from 3rd column onwards. I currently only kn

3条回答
  •  不知归路
    2020-12-08 02:27

    Sometimes it's easier to tell R what you don't want. In other words, exclude columns from the matrix using negative indexing:

    Here are two alternative ways that both produce the same results:

    A[, -(1:2)]
    A[, -seq_len(2)]
    

    Results:

         [,1] [,2] [,3] [,4] [,5] [,6]
    [1,]    3    4    5    6    7    8
    [2,]    3    4    5    6    7    8
    [3,]    3    4    5    6    7    8
    [4,]    3    4    5    6    7    8
    [5,]    3    4    5    6    7    8
    

    But to answer your question as asked: Use ncol to find the number of columns. (Similarly there is nrow to find the number of rows.)

    A[, 3:ncol(A)]
    
         [,1] [,2] [,3] [,4] [,5] [,6]
    [1,]    3    4    5    6    7    8
    [2,]    3    4    5    6    7    8
    [3,]    3    4    5    6    7    8
    [4,]    3    4    5    6    7    8
    [5,]    3    4    5    6    7    8
    

提交回复
热议问题