这是通过一些分组列收集一些数据的代码:
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。
编辑:这是一种黑客方式:
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
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句