我需要根据列类型对数据框进行子集化 - 例如,从包含100列的数据框中我需要仅保留类型为factor
或integer
的列。我已经编写了一个简短的函数来执行此操作,但CRAN上是否有任何更简单的解决方案或一些内置函数或包?
我目前的解决方案是获取所请求类型的变量名称:
varlist <- function(df=NULL, vartypes=NULL) {
type_function <- c("is.factor","is.integer","is.numeric","is.character","is.double","is.logical")
names(type_function) <- c("factor","integer","numeric","character","double","logical")
names(df)[as.logical(sapply(lapply(names(df), function(y) sapply(type_function[names(type_function) %in% vartypes], function(x) do.call(x,list(df[[y]])))),sum))]
}
函数varlist
的工作原理如下:
还有一些测试数据:
df <- read.table(file="http://archive.ics.uci.edu/ml/machine-learning-databases/statlog/german/german.data", sep=" ", header=FALSE, stringsAsFactors=TRUE)
names(df) <- c('ca_status','duration','credit_history','purpose','credit_amount','savings', 'present_employment_since','installment_rate_income','status_sex','other_debtors','present_residence_since','property','age','other_installment','housing','existing_credits', 'job','liable_maintenance_people','telephone','foreign_worker','gb')
df$gb <- ifelse(df$gb == 2, FALSE, TRUE)
df$property <- as.character(df$property)
varlist(df, c("integer","logical"))
我问,因为我的代码看起来非常神秘而且难以理解(即使对我来说,我已经在10分钟前完成了这个功能)。
答案 0 :(得分:17)
请执行以下操作:
df[,sapply(df,is.factor) | sapply(df,is.integer)]
答案 1 :(得分:2)
subset_colclasses <- function(DF, colclasses="numeric") {
DF[,sapply(DF, function(vec, test) class(vec) %in% test, test=colclasses)]
}
str(subset_colclasses(df, c("factor", "integer")))