Get the list of columns and its datatype in R

To get the list of columns and its datatype in R we use str() function and sapply along with  class function. let’s see with an example of each

Let’s first create the dataframe.

df1=data.frame(State=c('Arizona','Georgia', 'Newyork','Indiana','seattle','washington','Texas'),
               code=c('AZ','GA','NY','IN','ST','WT','TX'),
               Score=c(62,47,55,74,31,77,85),
               Index=c(6.8,7.1,8.9,7.4,9.4,7.7,9.2))

df1

So the dataframe will be

get the list of column and its dataype in R 1

 

Get the list of columns and its datatype – Method 1

sapply() along with class function is used to get the datatype of each column

## Get the list of columns and its datatype – Method1

sapply(df1,class)

Result:

get the list of column and its dataype in R 2

 

Get the list of columns and its datatype – Method 2

str() function is used to get the datatype of each column

## Get the list of columns and its datatype – Method2

str(df1)

Result:

get the list of column and its dataype in R 3

 

                                                                                         

Author

  • Sridhar Venkatachalam

    With close to 10 years on Experience in data science and machine learning Have extensively worked on programming languages like R, Python (Pandas), SAS, Pyspark.