3
votes

I am creating a simple 3x3 matrix with 9 values using the as.matrix() function. But the output I am seeing seems to be incorrect. What am I missing?

Here's what I am doing:

> s <- as.matrix(c(3,4,5,6,7,8,9,10,11),nrow = 3,ncol = 3)

What I expect to see:

> s
     [,1] [,2] [,3]
[1,]    3    6    9
[2,]    4    7   10
[3,]    5    8   11

But What I actually see:

> s
      [,1]
 [1,]    3
 [2,]    4
 [3,]    5
 [4,]    6
 [5,]    7
 [6,]    8
 [7,]    9
 [8,]   10
 [9,]   11
>

What am I missing?

The documentation for as.matrix() function says that nrow and ncol are used to defined the desired number of rows and columns. Any pointers?

2
To reiterate what @RonakShah said, if you look as the documentation for as.matrix vs. simply matrix, you will see that their API is different. matrix takes the arguments you have in your example (i.e. nrow and ncol) however as.matrix has the ellipsis ... as its second argument which are "additional arguments to be passed to or from methods".Joseph Wood

2 Answers

4
votes

as.matrix has no nrow and ncol parameter. What you need is actually matrix. Check ?as.matrix

matrix(c(3,4,5,6,7,8,9,10,11),nrow = 3,ncol = 3) 

#     [,1] [,2] [,3]
#[1,]    3    6    9
#[2,]    4    7   10
#[3,]    5    8   11
3
votes

You offered a vector as the first argument to as.matrix and the help page (Details section) says:

The default method for as.matrix calls as.vector(x), and hence e.g. coerces factors to character vectors.

When coercing a vector, it produces a one-column matrix, and promotes the names (if any) of the vector to the rownames of the matrix.

The usage section doesn't actually include ncol or nrow in the argument list to as.matrix. They just get ignored. The code to look at is:

as.matrix.default

That code does preserve matrix dimension if the first argument has them.

I find that using as.matrix is a good way to get print to produce a left-justified one column listing of atomic character vectors.