代码之家  ›  专栏  ›  技术社区  ›  Nova

在data.frame中提取每个字段的类;在new data.frame中汇总类

  •  0
  • Nova  · 技术社区  · 6 年前

    我有很多非常相似的.csv,我想通过编程检查它们的列类型是否相同。

    假设我导入了一个.csv作为data.frame,我想检查列类:

    library(tidyverse)
    
    test <- structure(list(Date = "6/15/2018", Time = structure(44255, class = c("hms", 
    "difftime"), units = "secs")), row.names = c(NA, -1L), class = c("tbl_df", 
    "tbl", "data.frame"))
    
    test
    ## A tibble: 1 x 2
    #  Date      Time  
    #  <chr>     <time>
    #1 6/15/2018 12:17 
    

    检查每个列的类,我可以看到 Time 列有两个类:

    map(test, class)
    # $`Date`
    # [1] "character"
    
    # $Time
    # [1] "hms"      "difftime"
    

    我想要的是一个理想的data.frame,它将显示:

    Date       Time
    character  hms, difftime
    

    这样我就可以很容易地比较不同的CSV。

    我想 map_dfr map_dfc 可能有用,但它们会返回错误。

    我也尝试了下面的方法,但是我以前还没有使用PrimeSeZyAL,我不能让它工作:

    test %>% data.frame() %>% 
      summarize_all(funs(paste0(collapse = ", ")))
    
    2 回复  |  直到 6 年前
        1
  •  2
  •   Calum You    6 年前

    你离得很近,你错过了 funs() 要求您指定列向量在函数调用中的位置 . . 所以应该是:

    test %>%
      summarize_all(funs(paste0(class(.), collapse = ", ")))
    

    然而, 函数() 已被软弃用,并从开始发出警告 dplyr 0.8.相反,您可以使用公式符号:

    library(tidyverse)
    test <- structure(list(Date = "6/15/2018", Time = structure(44255, class = c("hms", "difftime"), units = "secs")), row.names = c(NA, -1L), class = c("tbl_df", "tbl", "data.frame"))
    test %>%
      summarise_all(~ class(.) %>% str_c(collapse = ", "))
    #> # A tibble: 1 x 2
    #>   Date      Time         
    #>   <chr>     <chr>        
    #> 1 character hms, difftime
    

    如果你想尝试使用 purrr 样式语法,这里有一种方法可以使用 imap_dfr 排成一行。我们编写函数来为每一列返回一个命名向量,然后用 _dfr . (你可以用 gather 也要重塑宽格式版本)

    test %>%
      imap_dfr(~ tibble(colname = .y, classes = class(.x) %>% str_c(collapse = ", ")))
    #> # A tibble: 2 x 2
    #>   colname classes      
    #>   <chr>   <chr>        
    #> 1 Date    character    
    #> 2 Time    hms, difftime
    

    于2019年2月26日由 reprex package (v0.2.1)

        2
  •  1
  •   dww Jarretinha    6 年前

    你可以使用

    lapply(test, function(x) paste0(class(x), collapse = ', ')) %>% data.frame()