What is the difference between matrix() and as.matrix() functions in R?

matrix
r

#1

Hi,

What is the actual difference between the two functions to create matrices in r, matrix() and as.matrix()?
I get same result when applying the two functions

dt=c(1:6)
as.matrix(dt)
[,1]
[1,] 1
[2,] 2
[3,] 3
[4,] 4
[5,] 5
[6,] 6
matrix(dt)
[,1]
[1,] 1
[2,] 2
[3,] 3
[4,] 4
[5,] 5
[6,] 6

Thanks.


#2

Please see the below image:

As can be seen matrix recycles the elements when there are lesser number of data than dimensions,whereas as.matrix will just create a matrix from it’s first argument,and the dimensions are inferred from the input.
Hence,

> as.matrix(c(1:4),c(2:3))
     [,1]
[1,]    1
[2,]    2
[3,]    3
[4,]    4

The second argument has no effect on the structure of the matrix created.However if you give a dataframe as input.

dim(as.matrix(mtcars))
[1] 32 11

A matrix with the same dimensions as the dataframe is created.
Hope this helps!!