如何在 R 中获取数据框中所有列的类?
在本文中,我们将讨论如何在 R 编程语言中查找数据帧的所有类。
有两种方法可以在数据框中查找列的类。
- 使用 str()函数
- 使用 lapply()函数
方法一:使用str()函数
此函数将返回输入数据的类和值。
Syntax: str(dataframe_name)
示例: R 程序创建一个数据框并应用 str()函数。
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))
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))
输出:
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
方法二:使用lapply()函数
lapply()函数将只产生数据框列的类
Syntax: lapply(data_frame_name,class)
where: data_frame_name is the dataframe.
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"