Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Subsetting can convert matrix to vector #14

Open
danknights opened this issue Nov 15, 2013 · 1 comment
Open

Subsetting can convert matrix to vector #14

danknights opened this issue Nov 15, 2013 · 1 comment

Comments

@danknights
Copy link

I would add that indexing a matrix or array automatically drops dimensions of size 1. This can occasionally be convenient, as with a multidimensional array with a lot of useless dimensions, but in my experience it causes problems more often than not. If you subset only one row/column of a matrix, the result is just a vector, and functions that require a matrix (e.g. rowMeans) will obviously fail:

a <- matrix(seq(12),nr=3,nc=4)
rowMeans(a[1:2,])
[1] 5.5 6.5
rowMeans(a[1,])
Error in rowMeans(a[1, ]) :
'x' must be an array of at least two dimensions

Even if you explicitly create a 1-row matrix, subsetting will convert to vector:

a <- matrix(seq(5),nrow=1)
a
[,1] [,2] [,3] [,4] [,5]
[1,] 1 2 3 4 5
a[,]
[1] 1 2 3 4 5

This is intended behavior, but I find that I often want to explicitly keep all dimensions. For example, if you write a function that usually processes matrices with 2+ rows, but then one day pass it a one-row matrix, the first subsetting operation will convert it to a vector and will cause subsequent matrix operations to fail. Therefore you either need to explicitly handle operations on the one-row/one-column matrix separately, or you can make a habit of adding a "drop" parameter to the index, as I have done:

a <- matrix(seq(12),nr=3,nc=4)
rowMeans(a[1,,drop=F])
[1] 5.5

@kevinushey
Copy link

Thanks; this is a duplicate of #13.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

2 participants