How to convert Data type in R?

Description

To convert the data type uing R programming.

  • R Function : numeric(), is.character(),
    is.vector(), is.matrix(), is.data.frame()
  • Above functions return TRUE or FALSE
    indicating the type of data
  • R Function : numeric(), as.character(),
    as.vector(), as.matrix(),as.data.frame()
  • Above function convert data type into
    given type

#Data Type Conversion
#Input
#Simple Vector
vect_1<-c(1,3,2,5,2)
vect_2<-c(6,3,6,9,2)

#Numeric Vector
vect_num<-c(1.3,2.5,8.4,5.3,6.3)

#Charactor Vector
vect_char<-c(‘a’,’f’,’r’,’h’,’c’)

#Matrix
mat<-matrix(c(1:10),nrow=2)

#Data Frame
dat<-data.frame(vect_num,vect_char)

#Testing the data type
is.numeric(vect_num)
is.character(vect_char)
is.matrix(mat)
is.data.frame(dat)

#Converting data type
#From a vector to one long vector
vect<-c(vect_1,vect_2)
print(vect)

#From Vector to matrix
convt_mat<-cbind(vect_1,vect_2)
print(convt_mat)

#From Vector to Data Frame
convt_vect_dat<-data.frame(vect_1,vect_2)
print(convt_vect_dat)

#From Matrix to Vector
convt_mat_vect<-as.vector(mat)
print(convt_mat_vect)

#From Matrix to Data Frame
convt_mat_dat<-as.data.frame(mat)
print(convt_mat_dat)

#From Data Frame to Matrix
convt_dat_mat<-as.matrix(dat)
print(convt_dat_mat)

Leave Comment

Your email address will not be published. Required fields are marked *

clear formSubmit