使用 count/mutate 与 purrr:map 组合

Using count/mutate combo with purrr:map

示例数据:

       ï..Employee_Name       PositionID              Position State  Zip
  1:   Adinolfi, Wilson  K         19  Production Technician I    MA 1960
  2: Ait Sidi, Karthikeyan         27                  Sr. DBA    MA 2148
  3:     Akinkuolie, Sarah         20 Production Technician II    MA 1810
  4:          Alagbe,Trina         19  Production Technician I    MA 1886
  5:       Anderson, Carol         19  Production Technician I    MA 2169
 ---                                                                     
307:        Woodson, Jason         20 Production Technician II    MA 1810
308:     Ybarra, Catherine         19  Production Technician I    MA 2458
309:      Zamora, Jennifer          6                      CIO    MA 2067
310:           Zhou, Julia          9             Data Analyst    MA 2148
311:         Zima, Colleen         19  Production Technician I    MA 1730

我编写了自己的函数来计算数据框中变量的观察实例,然后将它们转换为因子:

HRdata_factor_count <- function(df, var) {
        df %>% 
        count(.data[[var]], sort = T) %>% 
        mutate(!!var := fct_reorder(factor(.data[[var]]), n))
    }

我想将它与 Purrr 包中的 map 函数一起使用,但出现以下错误:

> map(HRdata, ~HRdata_factor_count(.x))
 Error in UseMethod("count") : 
  no applicable method for 'count' applied to an object of class "character"

我该如何解决这个问题并让映射 return 列表包含我的 df 中每个变量的实例计数?

我试过了,但得到了一个奇怪的输出

    HRnames <- names(HRdata)
map2(HRdata, HRnames, ~HRdata_factor_count, df = .x, var =.y)

$Position
function(df, var) {
  df %>% 
    count(.data[[var]], sort = T) %>% 
    mutate(!!var := fct_reorder(factor(.data[[var]]), n))
}
<bytecode: 0x000001e2ce372f60>

$State
function(df, var) {
  df %>% 
    count(.data[[var]], sort = T) %>% 
    mutate(!!var := fct_reorder(factor(.data[[var]]), n))

根据你提供的数据,你可以试试purrrimap

imap(mtcars, ~count(tibble(.x), !!.y := factor(.x)))

作为函数

foo <- function(x, y) count(tibble(x), !!y := factor(x))
imap(mtcars, foo)
  • .x = 每列作为向量。检查 map(mtcars, ~.)imap(mtcars, ~.x)
  • .y =对应的列名:names(mtcars)

由于 count 需要 data.frame 或 tibble 作为输入,因此需要使用 tibble(x) 再次转换输入向量。因子在 count.

内指定

编辑:

像这样添加因子重新排序:

foo <- function(x, y){ count(tibble(x), tmp = factor(x)) %>% 
                       mutate(!!y := fct_reorder(tmp, n, .fun = sum)) %>% 
                       select(-tmp)}