按组复制数据框 [英] Replicate a data frame by group

查看:37
本文介绍了按组复制数据框的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有以下数据框:

df = structure(list(Group = c(1, 1, 1, 1, 2, 2, 2, 2, 2, 2, 3, 3, 
3), index = c(1, 2, 3, 4, 1, 2, 3, 4, 5, 6, 1, 2, 3)), row.names = c(NA, 
-13L), class = c("tbl_df", "tbl", "data.frame"))

我想根据组列复制列索引,一次每个数字连续出现n次,第二次所有数字作为一个组出现n 次,其中 n 是组的大小(类似于 reprepeach).

I would like to replicate the column index according to the Group column, one time with each number appearing n consecutive times, and a second time all the numbers appear as a group n times, where n is the size of the group (similarly to rep versus rep with each).

所以输出看起来像这样(我们只看第 1 组,因为它太长了):

So the output would look like this (lets look only at Group 1 because it is too long):

第一个选项:

df = structure(list(Group = c(1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 
1, 1, 1, 1), index = c(1, 1, 1, 1, 2, 2, 2, 2, 3, 3, 3, 3, 4, 
4, 4, 4)), row.names = c(NA, -16L), class = c("tbl_df", "tbl", 
"data.frame"))

第二个选项:

df = structure(list(Group = c(1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 
1, 1, 1, 1), index = c(1, 2, 3, 4, 1, 2, 3, 4, 1, 2, 3, 4, 1, 
2, 3, 4)), row.names = c(NA, -16L), class = c("tbl_df", "tbl", 
"data.frame"))

如何使用 group_by 执行此操作?

How do I do this with group_by?

推荐答案

你可以像这样使用 repslice

You could use rep and slice like this

library(dplyr)

选项 1:

df %>%
  group_by(Group) %>%
  slice(rep(seq_len(n()), each = n())) 

选项 2:

df %>%
  group_by(Group) %>%
  slice(rep(seq_len(n()), n()))

这篇关于按组复制数据框的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆