R语言 如何获得数据框架中所有列的类别

R语言 如何获得数据框架中所有列的类别

在这篇文章中,我们将讨论如何在R编程语言中找到数据框架的所有类别。

有两种方法可以找到数据框架中各列的类别

  • 使用str()函数
  • 使用lapply()函数

方法1:使用 str() 函数

这个函数将返回输入数据的类和值。

语法 :str(dataframe_name)

例子: R程序创建一个数据框架并应用str()函数。

# 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))

输出

    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

方法2:使用 lapply() 函数

lapply()函数将只产生数据框架列的类。

语法: lapply(data_frame_name,class)

其中: data_frame_name是数据框架。

R程序创建数据框架,并使用lapply()函数找到一个类。

# 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))

输出

    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"

Python教程

Java教程

Web教程

数据库教程

图形图像教程

大数据教程

开发工具教程

计算机教程