首页 文章

仅选择数据框中的数字列

提问于
浏览
130

假设你有一个像这样的data.frame:

x <- data.frame(v1=1:20,v2=1:20,v3=1:20,v4=letters[1:20])

您如何仅选择x中的数字列?

9 回答

  • 2

    另一种方式如下: -

    #extracting numeric columns from iris datset
    (iris[sapply(iris, is.numeric)])
    
  • 3

    这是其他答案的替代代码:

    x[, sapply(x, class) == "numeric"]
    

    data.table

    x[, lapply(x, is.numeric) == TRUE, with = FALSE]
    
  • 17

    如果您只对列名感兴趣,请使用:

    names(dplyr::select_if(train,is.numeric))
    
  • 2

    如果您有许多因子变量,则可以使用 select_if 功能 . 安装dplyr软件包 . 有许多功能通过满足条件来分离数据 . 你可以设定条件 .

    像这样使用 .

    categorical<-select_if(df,is.factor)
    str(categorical)
    
  • 53

    库PCAmixdata具有functon splitmix,它可以分割给定数据帧“YourDataframe”的定量(数值数据)和定性(分类数据),如下所示:

    install.packages("PCAmixdata")
    library(PCAmixdata)
    split <- splitmix(YourDataframe)
    X1 <- split$X.quanti(Gives numerical columns in the dataset) 
    X2 <- split$X.quali (Gives categorical columns in the dataset)
    
  • 1

    编辑:更新,以避免使用不明智的 sapply .

    由于数据框是一个列表,我们可以使用list-apply函数:

    nums <- unlist(lapply(x, is.numeric))
    

    然后是标准子集

    x[ , nums]
    
    ## don't use sapply, even though it's less code
    ## nums <- sapply(x, is.numeric)
    

    对于一个更现代的现代R我现在推荐

    x[ , purrr::map_lgl(x, is.numeric)]
    

    更少的代码,更少反映R的特殊怪癖,更简单,更强大,可用于数据库后端元素:

    dplyr::select_if(x, is.numeric)
    
  • 3

    dplyr软件包的 select_if( )功能是一个优雅的解决方案:

    library("dplyr")
    select_if(x, is.numeric)
    
  • 223

    来自基础包的 Filter() 是该用例的完美功能:您只需编写代码:

    Filter(is.numeric, x)
    

    它也比 select_if() 快得多:

    library(microbenchmark)
    microbenchmark(
        dplyr::select_if(mtcars, is.numeric),
        Filter(is.numeric, mtcars)
    )
    

    返回(在我的计算机上) Filter 的中位数为60微秒, dplyr 的中位数为21 000微秒(快350倍) .

  • 0

    这不是直接回答问题,但可能非常有用,特别是如果你想要除了你的id列和因变量之外的所有数字列 .

    numeric_cols <- sapply(dataframe, is.numeric) %>% which %>% 
                       names %>% setdiff(., c("id_variable", "dep_var"))
    
    dataframe %<>% dplyr::mutate_at(numeric_cols, function(x) your_function(x))
    

相关问题