r - 如何在 group_nest 之后取消嵌套 tibble?
问题描述
这是通过一些分组列收集一些数据的代码:
df <- tibble(data.frame(x=c(1,2,3), y=c(4,5,6)))
vars <- c('x', 'y')
df2 <- df %>%
group_nest(grouping_=across(all_of(vars))) %>%
mutate(result=1, data=NULL) %>%
unnest(cols=result)
现在 df2 有一个 grouping_ 数据框列,其中包含两个元素(x 和 y):
> str(df2)
tibble [3 × 2] (S3: tbl_df/tbl/data.frame)
$ grouping_: tibble [3 × 2] (S3: tbl_df/tbl/data.frame)
..$ x: num [1:3] 1 2 3
..$ y: num [1:3] 4 5 6
$ result : num [1:3] 1 1 1
如何展平 df2 以获得具有三列(x、y、结果)的数据框?
我无法工作:
> unnest(df2, cols=grouping_)
Error: Assigned data `map(data[[col]], as_df, col = col)` must be compatible with existing data.
x Existing data has 3 rows.
x Assigned data has 2 rows.
ℹ Only vectors of size 1 are recycled.
我正在使用 tidyverse 1.3.0,因此使用 dplyr 1.0.0。
编辑:这是一个hacky方式:
cbind(df2$grouping_,
df2 %>% mutate(grouping_=NULL))
也许这是最好的方式。
解决方案
尝试使用summarize()
而不是unnest()
.
df2 <- df %>%
group_nest(grouping_=across(all_of(vars))) %>%
mutate(result=1, data=NULL) %>%
summarize(grouping_, result)
df2
# A tibble: 3 x 3
x y result
<dbl> <dbl> <dbl>
1 1 4 1
2 2 5 1
3 3 6 1
str(df2)
tibble [3 x 3] (S3: tbl_df/tbl/data.frame)
$ x : num [1:3] 1 2 3
$ y : num [1:3] 4 5 6
$ result: num [1:3] 1 1 1
推荐阅读
- pyqt5 - 大小不等的子代的 QHBoxLayout 的替代方案
- c# - 根据数据注释反映表/列名称
- powerbi - 如何在powerbi中做countifs
- java - AccessibilityNodeInfo 的生命周期是什么?
- django - Django - RawPostDataException:从请求的数据流中读取后,您无法访问正文
- codeigniter - 在 codeiginiter php 的模式弹出窗口中停留在 HTML 选择的填充选项
- html - 当高度变化时,浮动右移到浮动左元素下
- html - 与 flex 结合使用时,CSS 文本对齐无法按预期工作
- matplotlib - 如何绘制连续的颜色条而不是离散的?
- acumatica - 扩展 CSAnswers DAC 时如何获取网格上属性值的控件类型?