r - 获取嵌套映射函数的标准 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
解决方案
你可以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
推荐阅读
- android - 使用 Firestore 查询仅获取用户尚未投票的民意调查
- python - “OneToOneField”的实例没有“用户名”成员 django 2.2.5
- javafx - 为什么 stage.setResizable(false); 和 stage.setMaximized(true); 不在 JavaFx 中工作?
- django - 稀疏索引用于优化 Pyomo 模型
- apache-kafka - Kafka-connect topic.prefix 不带表名
- php - 用php在字符串中的-elements之间添加逗号
- python - 需要将具有计数列的 SQL 语句转换为 SQL Alchemy
- java - 随机整数的堆栈溢出
- laravel - Laravel @include 控制器数据
- r - 在R中将变量转换为字符串