r - 在保留组的同时映射 tibble 列
问题描述
我有一个分组的小标题。我想map()
用来迭代 tibble 的列。在每一列中,我想map()
分别对每个组采取行动。换句话说,我想map()
尊重 tibble 的分组结构。
但map()
似乎不尊重小标题的分组结构。这是一个最小的例子:
library(dplyr)
library(purrr)
data(iris)
iris %>%
group_by(Species) %>%
map(length)
在 iris 数据集中,有 3 个物种和 4 列(不包括“物种”)。因此,我想map()
返回一个 3 × 4 = 12 个长度的列表,或者返回一个总共有 12 个长度的嵌套列表。但它返回一个包含 5 个元素的列表:每列一个,计算分组列。这五个元素中的每一个都是一列的总长度 (150)。如何调整上面的代码以提供我想要的结果?
在这个最小的例子中,一个令人满意的替代使用map()
是
iris %>%
group_by(Species) %>%
summarize(
mutate(across(everything(), length))
)
返回
# A tibble: 3 x 5
Species Sepal.Length Sepal.Width Petal.Length Petal.Width
* <fct> <int> <int> <int> <int>
1 setosa 50 50 50 50
2 versicolor 50 50 50 50
3 virginica 50 50 50 50
但在大多数情况下,这种替代方法是行不通的。问题是我通常想要summarize()
并mutate
返回loess()
对象,而不是整数。当我试图让他们返回loess()
对象时,他们会因错误而窒息,例如
Error: Problem with `summarise()` input `..1`.
x Input must be a vector, not a `loess` object.
解决方案
do
允许您一次在一个组上工作
编辑:正如你所说do
的被取代,这是更直接(和鼓励)的方式。(我在回答之前尝试过的do
问题是我错过了使用cur_data()
.)
colnms <- names(iris)[2:4]
colnms
# [1] "Sepal.Width" "Petal.Length" "Petal.Width"
iris %>%
group_by(Species) %>%
summarize(
other = colnms,
mdl = map(colnms, ~ loess(as.formula(paste("Sepal.Length ~", .x)),
data = cur_data()))
)
# Warning in simpleLoess(y, x, w, span, degree = degree, parametric = parametric, :
# pseudoinverse used at 0.0975
# Warning in simpleLoess(y, x, w, span, degree = degree, parametric = parametric, :
# neighborhood radius 0.2025
# Warning in simpleLoess(y, x, w, span, degree = degree, parametric = parametric, :
# reciprocal condition number 2.8298e-016
# Warning in simpleLoess(y, x, w, span, degree = degree, parametric = parametric, :
# There are other near singularities as well. 0.01
# # A tibble: 9 x 3
# # Groups: Species [3]
# Species other mdl
# <fct> <chr> <list>
# 1 setosa Sepal.Width <loess>
# 2 setosa Petal.Length <loess>
# 3 setosa Petal.Width <loess>
# 4 versicolor Sepal.Width <loess>
# 5 versicolor Petal.Length <loess>
# 6 versicolor Petal.Width <loess>
# 7 virginica Sepal.Width <loess>
# 8 virginica Petal.Length <loess>
# 9 virginica Petal.Width <loess>
推荐阅读
- elixir - 使用 Phoenix Elixir 提供静态图像
- vue.js - 模板表达式中有哪些全局变量?
- regex - 使用 htaccess 将所有子域重定向到新域
- python - 在 Flask-SqlAlchemy 和 MySQL 中处理数组
- c# - 如何让@RenderBody() 依次渲染?
- javascript - Treeshaking * 使用 Angular 导入?
- vb.net - 如何将不同的 EventArgs 传递给另一个子
- cassandra - 即使键空间的复制因子为 1,数据也会在我的第二个节点上复制/复制
- angular - 首先删除一些行并在删除后插入一些其他行的函数的问题
- javascript - 如何使用 javascript 和 html 显示特定的内容时区