簡體   English   中英

基於列類型的數據框中的子集變量

[英]Subset variables in data frame based on column type

我需要基於列類型對數據幀進行子集化-例如,從具有100列的數據幀中,我只需要保留那些類型factorinteger列。 我已經編寫了一個簡短的函數來執行此操作,但是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分鍾前完成了該功能)。

只需執行以下操作:

df[,sapply(df,is.factor) | sapply(df,is.integer)]
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")))

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM