Skip to main content

R: Data Class Conversion

Data in R can be converted from one class to the other. The functions are prefixed with 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.
Hence, if one wishes to convert a numeric data points 32, 35, 38, 29, 27, 40, and 33 into a character. Then, this is achieved by

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"
view raw DataConv.R hosted with ❤ by GitHub
Notice the difference between the output of the 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,

class(data.ch)
[1] "character"
view raw DataConv1.R hosted with ❤ by GitHub
Now consider this,

var1 <- c(5,6,3,4,5)
var2 <- c(11,12,13,13,15)
var3 <- c(26,25,24,22,23)
view raw DataConv2.R hosted with ❤ by GitHub
These objects are in numeric class, and converting these to data frame with three variables, would be

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"
view raw DataCon3.R hosted with ❤ by GitHub
Further to matrix class, we have

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"
view raw DataCon4.R hosted with ❤ by GitHub