[R] matrix -> delete last row -> list
Marc Schwartz
marc_schwartz at me.com
Fri Jul 3 17:41:22 CEST 2015
> On Jul 3, 2015, at 9: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.
>
> 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?
>
> I use R-version 2.15.3, but reconstructed this behavior in 3.2.0 as well.
>
> greetings
>
> --
> *Joscha Zander*
See:
http://cran.r-project.org/doc/FAQ/R-FAQ.html#Why-do-my-matrices-lose-dimensions_003f
mat <- matrix(1:12, ncol = 1)
> str(mat)
int [1:12, 1] 1 2 3 4 5 6 7 8 9 10 ...
> mat[-nrow(mat), ]
[1] 1 2 3 4 5 6 7 8 9 10 11
# This is a vector, not a list
> str(mat[-nrow(mat), ])
int [1:11] 1 2 3 4 5 6 7 8 9 10 …
> mat[-nrow(mat), , drop = FALSE]
[,1]
[1,] 1
[2,] 2
[3,] 3
[4,] 4
[5,] 5
[6,] 6
[7,] 7
[8,] 8
[9,] 9
[10,] 10
[11,] 11
# This is a matrix
> str(mat[-nrow(mat), , drop = FALSE])
int [1:11, 1] 1 2 3 4 5 6 7 8 9 10 …
Regards,
Marc Schwartz
P.S. are you restricted in being able to upgrade from a version of R that is two years old?
More information about the R-help
mailing list