- Modern R Programming Cookbook
- Jaynal Abedin
- 233字
- 2021-07-08 09:48:35
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:
- To convert a matrix to a data frame, the as.data.frame() function is enough:
M1ToData <- as.data.frame(M1)
- 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
- 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"
推薦閱讀
- Learning Python Web Penetration Testing
- Mastering Visual Studio 2017
- 一步一步學(xué)Spring Boot 2:微服務(wù)項目實戰(zhàn)
- Python 3.7網(wǎng)絡(luò)爬蟲快速入門
- Spring Cloud、Nginx高并發(fā)核心編程
- 實戰(zhàn)Java高并發(fā)程序設(shè)計(第3版)
- Java Web開發(fā)實例大全(基礎(chǔ)卷) (軟件工程師開發(fā)大系)
- Learning iOS Security
- Java自然語言處理(原書第2版)
- 計算機(jī)程序的構(gòu)造和解釋(JavaScript版)
- Zend Framework 2 Cookbook
- 深入實踐C++模板編程
- 計算機(jī)軟件項目實訓(xùn)指導(dǎo)
- Lync Server Cookbook
- Python程序設(shè)計