Class of a variable is important while analyzing the data in R. This ultimate tutorial includes three ways of discovering the class of each column in data frame. Find out how to obtain class of each column in R data frame.

Data frames can store different data types at the same time. Learning the variable class is essential for R users to know what type of data type in the each column of data frame. We learn three ways of obtaining the class of each column in R data frame. Firstly, we obtain a vector containing the types of columns in data frame. Secondly, we obtain a list involving the types of columns in R data frame. Last, we obtain the structure including the types of columns in data frame.

Let’s first construct an example data frame.

a <- c(1,3,5.4,-4) # numeric vector
b <- c("one","two","three","four") # character vector
c <- c(3L,-2L,4L,7L) # integer vector
d <- c(TRUE,FALSE,FALSE,TRUE) # logical vector
e <- c(-1+3i,2+2i,1-4i,2+3i) # complex vector
 
data <- data.frame(a,b,c,d,e)
data
##      a     b  c     d     e
## 1  1.0   one  3  TRUE -1+3i
## 2  3.0   two -2 FALSE  2+2i
## 3  5.4 three  4 FALSE  1-4i
## 4 -4.0  four  7  TRUE  2+3i

Check Out: How to Sort a Data Frame by Single and Multiple Columns in R

1) How to Find Class of Each Column in R Data Frame with sapply Function

In this part, we learn how to apply sapply function to find the class of the columns in data frame.

sapply(data, class) 
##           a           b           c           d           e 
##   "numeric" "character"   "integer"   "logical"   "complex"

Also Check: How to Remove Outliers from Data in R

2) How to Find Class of Each Column in R Data Frame with lapply Function

In this part, we use lapply function and obtain a list containing the variable types of data frame.

lapply(data, class) 
## $a
## [1] "numeric"
## 
## $b
## [1] "character"
## 
## $c
## [1] "integer"
## 
## $d
## [1] "logical"
## 
## $e
## [1] "complex"

Also Check: How to Change Working Directory in R

3) How to Find Class of Each Column in R Data Frame with str Function

We use str function to investigate the structure of data frame in R. The structure shows the class of each column, variable names, and the number of observations.

str(data) 
## 'data.frame':   4 obs. of  5 variables:
##  $ a: num  1 3 5.4 -4
##  $ b: chr  "one" "two" "three" "four"
##  $ c: int  3 -2 4 7
##  $ d: logi  TRUE FALSE FALSE TRUE
##  $ e: cplx  -1+3i 2+2i 1-4i ...

The application of the codes is available in our youtube channel below.

Subscribe to YouTube Channel

Don’t forget to check: How to Clean Data in R


Dr. Osman Dag