我使用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]
)
})
其他回答
下面是一个函数,它是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])的操作。
希望这对你有帮助!
要获得一个带有类型和类的漂亮Tibble:
purrr::map2_df(mtcars,names(mtcars), ~ {
tibble(
field = .y,
type = typeof(.x),
class_1 = class(.x)[1],
class_2 = class(.x)[2]
)
})
如果你以data.frame(而不是matrix)的形式导入csv文件,你也可以使用summary.default
summary.default(mtcars)
Length Class Mode
mpg 32 -none- numeric
cyl 32 -none- numeric
disp 32 -none- numeric
hp 32 -none- numeric
drat 32 -none- numeric
wt 32 -none- numeric
qsec 32 -none- numeric
vs 32 -none- numeric
am 32 -none- numeric
gear 32 -none- numeric
carb 32 -none- numeric
sapply(yourdataframe, class)
你的dataframe是你正在使用的数据帧的名称
另一种选择是使用purrr包的map函数。
library(purrr)
map(df,class)