Hi, when I assign a one row matrix to another variable, then somehow R automatically convert that varaible into a list. For example:> a = matrix (12, 3, 4) > b = a[1,] > b[1] 12 12 12 12 Is there a way to enable R automatically make b as a one row matrix , rather than explicitly assign like matrix (b, ncol=1). I have come across a couple of time, that when I try to check how many rows of the computed result matrix - nrow(,,,), because there is only one row, the program failed as R tried to interpret it as a list. Can some one help? -- Waverley @ Palo Alto [[alternative HTML version deleted]]
On Fri, 2006-11-03 at 14:12 -0800, Waverley wrote:> Hi, > > when I assign a one row matrix to another variable, then somehow R > automatically convert that varaible into a list.A 'vector', not a 'list'> For example: > > > a = matrix (12, 3, 4) > > b = a[1,] > > b > [1] 12 12 12 12 > > Is there a way to enable R automatically make b as a one row matrix , rather > than explicitly assign like matrix (b, ncol=1). I have come across a > couple of time, that when I try to check how many rows of the computed > result matrix - nrow(,,,), because there is only one row, the program failed > as R tried to interpret it as a list. > > Can some one help?This is actually a FAQ: http://cran.r-project.org/doc/FAQ/R-FAQ.html#Why-do-my-matrices-lose-dimensions_003f HTH, Marc Schwartz
On 11/3/06, Waverley <waverley.paloalto at gmail.com> wrote:> Hi,> For example: > > > a = matrix (12, 3, 4) > > b = a[1,] > > b > [1] 12 12 12 12 >It doesn't have anything to do with one-row matrices, at least in your example, since that isn't what you made. Instead, you created a matrix with 3 rows, 4 columns, and all values equal to 12.> a <- matrix(12, 3, 4) > a[,1] [,2] [,3] [,4] [1,] 12 12 12 12 [2,] 12 12 12 12 [3,] 12 12 12 12> a[1,][1] 12 12 12 12 You probably intended> a <- matrix(c(12, 3, 4), nrow=1)> a[,1] [,2] [,3] [1,] 12 3 4 But to solve what I think you were actually asking, even though it wasn't reflected in your example... By default, R drops unused dimensions when subsetting. You can override this behavior> b <- a[1, ,drop=FALSE]> b[,1] [,2] [,3] [1,] 12 3 4 See: ?subset help('[') ?matrix Sarah -- Sarah Goslee http://www.functionaldiversity.org