官术网_书友最值得收藏!

How to do it…

There are several ways to create a matrix, but the most convenient way to create a matrix is through the use of the matrix() function from base R. Let's perform the following steps to learn about creating a matrix:

  1. Execute the following code snippet that depicts a matrix of order 2 x 2 with all elements equal to 1:
        matA <- matrix(1, nrow=2, ncol=2)
matB <- matrix(1:9, nrow=3, ncol=3, byrow=TRUE)
  1. There are alternative ways to create a matrix, such as, binding two or more vectors to create a two-dimensional representation as follows:
        Vec1 <- 1:3
Vec2 <- 3:1
  1. Now, bind the preceding two vectors as two different rows to create a matrix as follows:
        matC <- rbind(Vec1, Vec2)
  1. Alternatively, you could bind the two vectors as a column of a matrix as follows:
        matD <- cbind(Vec1, Vec2)
  1. Since a matrix is a two-dimensional arrangement of vectors, you can create a matrix using the array function by specifying two dimensions. For example, take a look at the following code snippet:
        matE <- array(1:9, dim=c(3,3))
  1. Once you have created a matrix, you might want to check whether you have created a matrix based on the specification of R. To test the object, you can use the is.matrix() function. If the output is TRUE, then you are certain that you have created the matrix correctly:
        is.matrix(matA)
  1. To determin the number of rows/columns, you can use either the nrow() or ncol() function as follows:
        nrow(matA)
ncol(matA)
  1. You can access a specific element of a matrix by giving the row index and column index within square brackets as follows:
        matA[1, 2]
  1. It will give the second value of the first row and alternatively, the first value of the second column. Let's assume you omit one index and provide only the other one as follows:
        matA[2, ]

Then, it will give only the values of the second row of the matrix.

主站蜘蛛池模板: 濉溪县| 木兰县| 腾冲县| 基隆市| 台湾省| 莒南县| 建德市| 阿克陶县| 鹤庆县| 盘锦市| 纳雍县| 肇源县| 凤山市| 奉化市| 资兴市| 营口市| 巩义市| 洪洞县| 沙雅县| 阿拉尔市| 武汉市| 司法| 谢通门县| 津南区| 阿克陶县| 伊春市| 兰州市| 承德市| 东乌珠穆沁旗| 合作市| 花莲市| 志丹县| 海原县| 宜城市| 洞头县| 忻州市| 永宁县| 元谋县| 凤凰县| 五家渠市| 大英县|