Reputation: 53
When I subset just one row of a matrix and pass that to nrow as nrow(x[1,])
or nrow(x[2,])
it returns a NULL
value instead of 1
.
However if I subset more than one row then nrow(x[1:2,])
returns 2
which is a correct value.
Need help on how to handle cases like nrow(x[i,])
.
Thanks in advance.
Upvotes: 0
Views: 2828
Reputation: 11
You can also use drop = FALSE
in subsetting the matrix, which provides R from dropping the matrix class:
(m <- matrix(1, 3, 3))
#> [,1] [,2] [,3]
#> [1,] 1 1 1
#> [2,] 1 1 1
#> [3,] 1 1 1
class(m[1, ])
#> [1] "numeric"
class(m[1, , drop = FALSE])
#> [1] "matrix" "array"
Then nrow()
returns the desired result:
nrow(m[1, , drop = FALSE])
#> [1] 1
nrow(m[2, , drop = FALSE])
#> [1] 1
Upvotes: 1
Reputation: 7928
You can use NCOL()
and NROW()
, they treat vectors as 1-column matrix, i.e
x <- structure(c(1, 1, 1, 1, 1, 1, 1, 1, 1), .Dim = c(3L, 3L))
x
#> [,1] [,2] [,3]
#> [1,] 1 1 1
#> [2,] 1 1 1
#> [3,] 1 1 1
Now, as you point out nrow(x[1,])
and nrow(x[2,])
return NULL
nrow(x[1,])
#> NULL
nrow(x[2,])
#> NULL
but,
NCOL(x[1,])
#> [1] 1
NROW(x[1,])
#> [1] 3
You could also make the object a tibble, but I guess you don't want to go there with a matrix. Regardless,
# install.packages(c("tidyverse"), dependencies = TRUE)
library(tidyverse)
z <- x %>% as_tibble()
nrow(z[1,])
#> [1] 1
ncol(z[1,])
#> [1] 3
Upvotes: 1