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

How to do it…

The object conversion in R is very intuitive and easy to understand. The name of the function itself tells the story. Let's perform the following steps to convert a matrix to a data frame and a data frame to a matrix:

  1. To convert a matrix to a data frame, the as.data.frame() function is enough:
        M1ToData <- as.data.frame(M1)
  1. To check whether the newly created object M1ToData is a data frame or not, you can use either the class() function or the str() function. The str() function will give the results along with the type of each column. The output of the str() function is as follows:
        > str(M1ToData)
'data.frame': 3 obs. of 3 variables:
$ V1: int 1 4 7
$ V2: int 2 5 8
$ V3: int 3 6 9
  1. Notice that the columns got new names such as V1, V2, and V3 because a data frame must have a name for each column. If there is no name specified, then the default name will be V1, V2, and so on. To convert a data frame to a matrix, execute the following code snippet:
        D1ToMatrix <- as.matrix(D1)
> str(D1ToMatrix)
chr [1:5, 1:2] "1" "3" "2" "4" "5" "Cricket" "Football"
"Basketball" "Rugby" "Baseball"
- attr(*, "dimnames")=List of 2
..$ : NULL
..$ : chr [1:2] "x1" "x2"

Since one of the columns of the data frame was of character type, the resultant matrix is converted to character type. The resultant matrix is a matrix of five rows and two columns. Since the conversion has been done from a data frame and each column had a name on it, the matrix also contains those column names as follows:

        colnames(D1ToMatrix)
> colnames(D1ToMatrix)
[1] "x1" "x2"
主站蜘蛛池模板: 绥江县| 高碑店市| 宿州市| 尼玛县| 保山市| 永川市| 抚松县| 夏河县| 平阴县| 灵石县| 蒙山县| 泽普县| 清水河县| 奉新县| 包头市| 平谷区| 祁阳县| 航空| 汉寿县| 舟山市| 乐陵市| 绵竹市| 昌平区| 应用必备| 七台河市| 平顺县| 色达县| 仁寿县| 阜南县| 唐海县| 蓬溪县| 大安市| 乐山市| 西乌珠穆沁旗| 西峡县| 浑源县| 阳西县| 祁连县| 祁东县| 托克托县| 湘潭市|