[R] matrix -> delete last row -> list

Sarah Goslee sarah.goslee at gmail.com
Fri Jul 3 17:43:21 CEST 2015


Hi,

On Fri, Jul 3, 2015 at 10:33 AM, Zander, Joscha <joscha.zander at roche.com>
wrote:
> Good day R-community,
>
> i just wondered if it is a bug or a feature...
>
> When i have a matrix "mat" with one column and i delete the last row with
>
> mat <- mat[-nrow(mat),] the result is a list.

I have no idea how you're getting a list from a matrix (see below). Perhaps
you mean a data frame?


> So my next call mat[10,] will throw an "wrong dimension" error.
> The proper call must be:
>
> mat <- as.matrix(mat[-nrow(mat),])
>
> So is this desired behavior or a bug?

If you check
?"["
you'll see the drop argument, which is what I guess you want. Compare:

> mat <- matrix(1:6, nrow=2)
> mat <- mat[-nrow(mat), ]
> class(mat) # not a list
[1] "integer"
> dim(mat)
NULL
> is.list(mat) # see? really not a list
[1] FALSE
> mat
[1] 1 3 5


> mat <- matrix(1:6, nrow=2)
> mat <- mat[-nrow(mat), , drop=FALSE]
> class(mat)
[1] "matrix"
> dim(mat)
[1] 1 3
> mat
     [,1] [,2] [,3]
[1,]    1    3    5



> I use R-version 2.15.3, but reconstructed this behavior in 3.2.0 as well.
>
> greetings
>
> --
>  *Joscha Zander*
>--
Sarah Goslee
http://www.functionaldiversity.org

	[[alternative HTML version deleted]]



More information about the R-help mailing list