简体   繁体   中英

R and matrix with 1 row

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]

   ...
   data.frame(y,x)

the idea is that i have a vector y and matrix x. Y can contain some NA values, which i want to find and remove the index of those values from both vector and the matrix.

Later i want to frame y with x. The problem is, however, when there is only one value that is not NA in y. It means i have to remove all but 1 element from y and all but 1 row from x, this having matrix with only 1 row, which seems to be converted to numeric, which seems to break the data.frame operation. I expected it to return frame containing 1 row: y x1 x2 .., instead i get:

   y    x
1  0 12.0
2  0 14.8
3  0 14.2
4  0 14.8
5  0  2.0
6  0  4.0
7  0  1.0
8  0  2.0
9  0 26.0
10 0  4.0
11 0  6.0
12 0  2.0
13 0 16.0

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

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 .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM