【问题标题】:Using count/mutate combo with purrr:map将计数/变异组合与 purrr:map 一起使用
【发布时间】:2021-05-04 14:43:32
【问题描述】:

样本数据:

       ï..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(HRdata, ~HRdata_factor_count(.x))
 Error in UseMethod("count") : 
  no applicable method for 'count' applied to an object of class "character"

我将如何解决此问题并让 map 返回一个列表,其中包含我的 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))

【问题讨论】:

  • 你能添加一些示例数据吗? HRdata 是列表吗?此外,您可以在count 内转换,如mtcars %&gt;% count(cyl = factor(cyl)) %&gt;% glimpse()
  • 还要检查您的 HRdata_factor_count() 函数是否指定了 2 个输入变量,dfvar。在您的 map() 电话中,您只提供 1,即 .x
  • 我已添加示例数据

标签: r purrr


【解决方案1】:

根据你提供的数据,你可以试试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)}

【讨论】:

  • 我创建的函数有什么办法吗?我使用 map2 进行了尝试,并在上面更新了我的查询
  • 没有。你的功能不会那样工作。请参阅 Ray 我的提示的评论,即 .x 是向量而不是 data.frame。
  • 嘿,你帮了我很多,让我回到 Ray 的评论。我意识到我不需要使用我写的函数。最后,我只是在我的数据框上使用了一个带有表函数的法线贴图,它工作得很好。我仍在试图弄清楚如何同时进行 fct_reorder ,但我认为它与管道有关。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2020-11-20
  • 1970-01-01
  • 2012-09-10
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多