LOFTER for ipad —— 让兴趣,更有趣

点击下载 关闭
12 Matrices
子苔 2019-03-17

Matrices

In R, a matrix is a collection of elements of the same data type (numeric, character, or logical) arranged into a fixed number of rows and columns. Since you are only working with rows and columns, a matrix is called two-dimensional.

You can construct a matrix in R with the matrix() function. Consider the following example:

matrix(1:9, byrow = TRUE, nrow = 3, ncol = 3)

In the matrix() function:

  • The first argument is the collection of elements that R will arrange into the rows and columns of the matrix. Here, we use 1:9 which constructs the vector c(1, 2, 3, 4, 5, 6, 7, 8, 9).

  • The argument byrow indicates that the matrix is filled by the rows. This means  that the matrix is filled from left to right and when the first row is completed,  the filling continues on the second row. If we want the matrix to be filled by the columns, we just place byrow = FALSE.每一行从左到右都填满   

     > matrix(1:20,byrow=TRUE,nrow=5)
         [,1] [,2] [,3] [,4]
    [1,]    1    2    3    4
    [2,]    5    6    7    8
    [3,]    9   10   11   12
    [4,]   13   14   15   16
    [5,]   17   18   19   20

     

    > matrix(1:20,byrow=FALSE,nrow=5)
         [,1] [,2] [,3] [,4]
    [1,]    1    6   11   16
    [2,]    2    7   12   17
    [3,]    3    8   13   18
    [4,]    4    9   14   19
    [5,]    5   10   15   20

  • The third argument nrow indicates that the matrix should have three rows.

  • The fourth argument ncol indicates the number of columns that the matrix should have


推荐文章
评论(0)
联系我们|招贤纳士|移动客户端|风格模板|官方博客|侵权投诉 Reporting Infringements|未成年人有害信息举报 0571-89852053|涉企举报专区
网易公司版权所有 ©1997-2024  浙公网安备 33010802010186号 浙ICP备16011220号-11 增值电信业务经营许可证:浙B2-20160599
网络文化经营许可证: 浙网文[2022]1208-054号 自营经营者信息 工业和信息化部备案管理系统网站 12318全国文化市场举报网站
网信算备330108093980202220015号 网信算备330108093980204230011号
分享到
转载我的主页