【问题标题】:Getting standard purrr parent variable of a nested map function获取嵌套映射函数的标准 purrr 父变量
【发布时间】:2019-11-25 09:38:11
【问题描述】:

下面的代码按所有字符变量分组并对所有数字变量求和。获取我使用的字符变量map_lgl 并且仍然能够引用外部.x(这是小标题)我不得不使用管道。是否可以在没有管道的情况下使用map_lgl

library(tidyverse)

l <- list()
l$d1 <- tribble(~a, ~b, ~x,
                "a", "mm", 4,
                "a", "kk", 8,
                "a", "mm", 2)
l$d2 <- tribble(~a, ~d, ~y,
                "b", "u", 4,
                "b", "u", 1,
                "c", "u", 9)

map(l,
    ~.x %>%
      group_by(.dots = tbl_vars(.)[.x %>%
                                       map_lgl(is.character)]) %>%
      # how can I avoid the pipe in this case?
      summarise_all(sum) %>%
      ungroup())  

# result:
# $d1
# # A tibble: 2 x 3
# a     b         x
# <chr> <chr> <dbl>
# 1 a     kk        8
# 2 a     mm        6
# 
# $d2
# # A tibble: 2 x 3
# a     d         y
# <chr> <chr> <dbl>
# 1 b     u         5
# 2 c     u         9

【问题讨论】:

    标签: r dplyr tidyverse purrr


    【解决方案1】:

    你可以在这里使用group_by_if

    library(dplyr)
    
    purrr::map(l, ~.x %>% group_by_if(is.character) %>% summarise_all(sum))
    #OR if there are other columns which are not numeric
    #purrr::map(l, ~.x %>% group_by_if(is.character) %>% summarise_if(is.numeric, sum))
    
    #$d1
    # A tibble: 2 x 3
    # Groups:   a [1]
    #  a     b         x
    #  <chr> <chr> <dbl>
    #1 a     kk        8
    #2 a     mm        6
    
    #$d2
    # A tibble: 2 x 3
    # Groups:   a [2]
    #  a     d         y
    #  <chr> <chr> <dbl>
    #1 b     u         5
    #2 c     u         9
    

    【讨论】:

    • group_by_if 在这种情况下肯定更有意义。不过,是否可以检索父 .x
    • @r.user.05apr 我不确定我是否理解。 retrieve the parent .x 是什么意思?这里的用例是什么?
    猜你喜欢
    • 2019-12-27
    • 1970-01-01
    • 2018-03-05
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-07-28
    相关资源
    最近更新 更多