Data Class Conversion
[This article was first published on Analysis with R, and kindly contributed to R-bloggers]. (You can report issue about the content on this page here)
Want to share your content on R-bloggers? click here if you have a blog, or here if you don't.
Data in R can be converted from one class to the other. The function is 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:Want to share your content on R-bloggers? click here if you have a blog, or here if you don't.
- numeric – as.numeric
- vector – as.vector
- character – as.character
- matrix – as.matrix
- 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" |
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" |
To leave a comment for the author, please follow the link and comment on their blog: Analysis with R.
R-bloggers.com offers daily e-mail updates about R news and tutorials about learning R and many other topics. Click here if you're looking to post or find an R/data-science job.
Want to share your content on R-bloggers? click here if you have a blog, or here if you don't.