我有以下数据框架:
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"))我想根据Group列复制列索引,每一个数字连续出现n一次,第二次所有数字都显示为组n次数,其中n是组的大小(类似于rep和each的rep )。
所以输出应该是这样的(让我们只看第1组,因为它太长了):
第一种选择:
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完成此操作?
发布于 2019-05-30 11:14:15
你可以像这样使用rep和slice
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()))发布于 2019-05-30 11:18:44
您可以使用do和lapply的组合来复制整个组
df %>% group_by(Group) %>%
do(lapply(.,rep,times=nrow(.)) %>% as.data.frame())
df %>% group_by(Group) %>%
do(lapply(.,rep,each=nrow(.)) %>% as.data.frame())发布于 2019-05-30 13:53:41
我们可以使用uncount
library(tidyverse)
df %>%
group_by(Group) %>%
uncount(n())
# A tibble: 61 x 2
# Groups: Group [3]
# Group index
# <dbl> <dbl>
# 1 1 1
# 2 1 1
# 3 1 1
# 4 1 1
# 5 1 2
# 6 1 2
# 7 1 2
# 8 1 2
# 9 1 3
#10 1 3
# … with 51 more rows或者使用data.table
library(data.table)
setDT(df)[, .SD[rep(seq_len(.N), .N)], Group]或使用base R
do.call(rbind, lapply(split(df, df$Group),
function(x) x[rep(seq_len(nrow(x)), nrow(x)),]))https://stackoverflow.com/questions/56376835
复制相似问题