Skip to content
Related Articles

Related Articles

Improve Article
Save Article
Like Article

How to get the classes of all columns in a dataframe in R ?

  • Last Updated : 16 May, 2021

In this article, we will discuss how to find all the classes of the dataframe in R Programming Language.

There are two methods to find the classes of columns in the dataframe.

  • Using str() function
  • Using lapply() function

Method1 : Using str() function

This function will return the class and value of the input data.

Syntax: str(dataframe_name)



Example: R program to create a dataframe and apply str() function.

R




# create vector with integer 
# elements
a = c(7058, 7059, 7072, 7075)
  
# create vector with floating
# point elements
c = c(98.00, 92.56, 90.00, 95.00)
  
# pass these vectors as inputs to
# the dataframe
data = data.frame( id = a, percentage = c)
print(data)
  
# apply str function to get columns 
# class of the dataframe
print(str(data))

Output:

    id percentage
1 7058      98.00
2 7059      92.56
3 7072      90.00
4 7075      95.00
'data.frame':    4 obs. of  2 variables:
 $ id        : num  7058 7059 7072 7075
 $ percentage: num  98 92.6 90 95
NULL

Method 2: Using lapply() function

lapply() function will result only the class of the dataframe column

Syntax: lapply(data_frame_name,class)

where: data_frame_name is the dataframe.

R program to create the dataframe and use lapply() function to find a class.

R




# create vector with integer 
# elements
a = c(7058, 7059, 7072, 7075)
  
# create vector with string elements
b = c("sravan", "jyothika", "harsha", "deepika")
  
# create vector with floating point
# elements
c = c(98.00, 92.56, 90.00, 95.00)
  
# pass these vectors as inputs to 
# the dataframe
data = data.frame(id = a, names = b, percentage = c)
print(data)
  
# lapply function to get columns class 
# of the dataframe
print(lapply(data, class))

Output:

    id    names percentage
1 7058   sravan      98.00
2 7059 jyothika      92.56
3 7072   harsha      90.00
4 7075  deepika      95.00
$id
[1] "numeric"

$names
[1] "factor"

$percentage
[1] "numeric"



My Personal Notes arrow_drop_up
Recommended Articles
Page :

Start Your Coding Journey Now!