Does the c command create a row vector or a column vector by default in R

Neither. A vector does not have a dimension attribute by default, it only has a length.

If you look at the documentation on matrix arithmetic, help("%*%"), you see that:

Multiplies two matrices, if they are conformable. If one argument is a vector, it will be promoted to either a row or column matrix to make the two arguments conformable. If both are vectors of the same length, it will return the inner product (as a matrix).

So R will interpret a vector in whichever way makes the matrix product sensible.

Some examples to illustrate:

> b <- c(7,10)
> b
[1]  7 10
> dim(b) <- c(1,2)
> b
     [,1] [,2]
[1,]    7   10
> dim(b) <- c(2,1)
> b
     [,1]
[1,]    7
[2,]   10
> class(b)
[1] "matrix"
> dim(b) <- NULL
> b
[1]  7 10
> class(b)
[1] "numeric"

A matrix is just a vector with a dimension attribute. So adding an explicit dimension makes it a matrix, and R will do that in whichever way makes sense in context.

And an example of the behavior in the context of matrix multiplication:

> m <- matrix(1:2,1,2)
> m
     [,1] [,2]
[1,]    1    2
> m %*% b
     [,1]
[1,]   27
> m <- matrix(1:2,2,1)
> m %*% b
     [,1] [,2]
[1,]    7   10
[2,]   14   20

Leave a Comment