R and matrix with 1 row

后端 未结 2 1767
臣服心动
臣服心动 2020-12-06 21:18

is it possible to have a matrix with 1 row only in R?

Here is my code:

   nas <- which(!is.na(y))   
   x <- x[nas,]
   y <- y[nas]

   ...
         


        
相关标签:
2条回答
  • 2020-12-06 21:50

    You need to specify drop = FALSE to stop R coercing a matrix or array to the lowest possible number of dimensions. See ?`[` for more details.

    x <- matrix(1:4,ncol=2)
    x[1,]
    ## [1] 1 2
    x[1,,drop=F]
    ##      [,1] [,2]
    ## [1,]    1    3
    
    0 讨论(0)
  • 2020-12-06 21:58

    Sure it is, as Patrick Li, notes in the comment, but not if you use the vector() function to create it.

    So:

    R> matrix(1:4, nrow=1)
         [,1] [,2] [,3] [,4]
    [1,]    1    2    3    4
    R> matrix(1:4, ncol=1)
         [,1]
    [1,]    1
    [2,]    2
    [3,]    3
    [4,]    4
    R> matrix(1:4, ncol=2)
         [,1] [,2]
    [1,]    1    3
    [2,]    2    4
    R>     
    

    For more options regarding use of matrix(), see its help page. For more on very basic issues (hint: drop=FALSE), see the R FAQ.

    0 讨论(0)
提交回复
热议问题