首页 > 解决方案 > 获取嵌套映射函数的标准 purrr 父变量

问题描述

下面的代码按所有字符变量分组并对所有数字变量求和。获取我使用的字符变量map_lgl并且仍然能够引用外部.x(这是 tibble)我不得不使用管道。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

标签: rdplyrtidyversepurrr

解决方案


你可以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

推荐阅读