我使用R并使用read.csv()将数据加载到数据帧中。如何确定数据帧中每一列的数据类型?
当前回答
要获得一个带有类型和类的漂亮Tibble:
purrr::map2_df(mtcars,names(mtcars), ~ {
tibble(
field = .y,
type = typeof(.x),
class_1 = class(.x)[1],
class_2 = class(.x)[2]
)
})
其他回答
简单地传递你的数据帧到下面的函数:
data_types <- function(frame) {
res <- lapply(frame, class)
res_frame <- data.frame(unlist(res))
barplot(table(res_frame), main="Data Types", col="steelblue", ylab="Number of Features")
}
生成数据帧中所有数据类型的图表。对于虹膜数据集,我们得到以下结果:
data_types(iris)
另一种选择是使用purrr包的map函数。
library(purrr)
map(df,class)
下面是一个函数,它是helpRFunctions包的一部分,它将返回数据帧中所有不同数据类型的列表,以及与该类型相关的特定变量名。
install.package('devtools') # Only needed if you dont have this installed.
library(devtools)
install_github('adam-m-mcelhinney/helpRFunctions')
library(helpRFunctions)
my.data <- data.frame(y=rnorm(5),
x1=c(1:5),
x2=c(TRUE, TRUE, FALSE, FALSE, FALSE),
X3=letters[1:5])
t <- list.df.var.types(my.data)
t$factor
t$integer
t$logical
t$numeric
然后,您可以执行类似var(my.data[t$numeric])的操作。
希望这对你有帮助!
我建议
sapply(foo, typeof)
如果你需要数据帧中向量的实际类型。Class()有点不同。
如果你不需要作为一个向量来获取这个信息(也就是说,你不需要它来做其他的编程),只需要使用str(foo)。
在这两种情况下,foo将被替换为数据帧的名称。
因为说得不清楚,我补充一下:
我正在寻找一种方法来创建一个表,其中保存所有数据类型的出现次数。
假设我们有一个data.frame,有两个数字列和一个逻辑列
dta <- data.frame(a = c(1,2,3),
b = c(4,5,6),
c = c(TRUE, FALSE, TRUE))
您可以用它来总结每种数据类型的列数
table(unlist(lapply(dta, class)))
# logical numeric
# 1 2
如果您有很多列,并且想要快速浏览,那么这个方法非常方便。
这个解决方案的灵感来自@Cybernetic的答案。