8

我需要根据列类型对数据框进行子集化 - 例如,从具有 100 列的数据框中,我只需要保留那些类型为factoror的列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工作原理如下:

  1. 对于每个请求的类型和数据框中的每一列,调用“is.TYPE”函数
  2. 对每个变量进行求和测试(布尔值自动转换为整数)
  3. 将结果转换为逻辑向量
  4. 数据框中的子集名称

和一些数据来测试它:

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 分钟前完成了该功能)。

4

2 回答 2

19

只需执行以下操作:

df[,sapply(df,is.factor) | sapply(df,is.integer)]
于 2013-07-31T07:54:56.020 回答
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")))
于 2013-07-31T07:58:22.987 回答