Data in R can be converted from one class to the other. The functions are prefixed with
Notice the difference between the output of the
Now consider this,
These objects are in numeric class, and converting these to data frame with three variables, would be
Further to matrix class, we have
as.
then followed by the name of the data class that we wish to convert to. Data class in R are the following:- numeric -
as.numeric
; - vector -
as.vector
; - character -
as.character
; - matrix -
as.matrix
; and, - data frame -
as.data.frame
.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
data <- c(32, 35, 38, 29, 27, 40, 33) | |
data | |
[1] 32 35 38 29 27 40 33 | |
data.ch <- as.character(data) | |
data.ch | |
[1] "32" "35" "38" "29" "27" "40" "33" |
data
object and the converted one, data.ch
? The output differs only with this character, "
. This character that encloses every data points suggests that the data is now in character form. And this can be verified using the function class
,
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
class(data.ch) | |
[1] "character" |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
var1 <- c(5,6,3,4,5) | |
var2 <- c(11,12,13,13,15) | |
var3 <- c(26,25,24,22,23) |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
data.f1 <- data.frame(var1, var2, var3) | |
data.f1 | |
var1 var2 var3 | |
1 5 11 26 | |
2 6 12 25 | |
3 3 13 24 | |
4 4 13 22 | |
5 5 15 23 | |
class(data.f1) | |
[1] "data.frame" |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
data.mat <- as.matrix(data.f1) | |
data.mat | |
var1 var2 var3 | |
[1,] 5 11 26 | |
[2,] 6 12 25 | |
[3,] 3 13 24 | |
[4,] 4 13 22 | |
[5,] 5 15 23 | |
class(data.mat) | |
[1] "matrix" |