我们用'add_count'创建一个频率列,按'Col1'、'Col2'分组,然后创建一个序列命名列('nm1'),使用complete扩展缺失组合的数据并重塑为'宽'格式与pivot_wider
library(dplyr)
library(tidyr)
library(stringr)
df1 %>%
add_count(Col1, Col2) %>%
group_by(Col1, Col2) %>%
slice(seq_len(5)) %>%
mutate(nm1 = str_c("NewCol", row_number())) %>%
complete(nm1 = str_c("NewCol", 1:5)) %>%
ungroup %>%
dplyr::select(-Col3) %>%
fill(n) %>%
pivot_wider(names_from = nm1, values_from = Col4)
# A tibble: 2 x 8
# Col1 Col2 n NewCol1 NewCol2 NewCol3 NewCol4 NewCol5
# <int> <int> <int> <int> <int> <int> <int> <int>
#1 1 4000 1 6 NA NA NA NA
#2 1 7000 2 6 7 NA NA NA
使用第二个数据集
df2 %>%
add_count(Col1, Col2) %>%
group_by(Col1, Col2) %>%
slice(seq_len(5)) %>%
mutate(nm1 = str_c("NewCol", row_number())) %>%
complete(nm1 = str_c("NewCol", 1:5)) %>%
ungroup %>%
dplyr::select(-Col3) %>%
fill(n) %>%
pivot_wider(names_from = nm1, values_from = Col4)
# A tibble: 2 x 8
# Col1 Col2 n NewCol1 NewCol2 NewCol3 NewCol4 NewCol5
# <int> <int> <int> <int> <int> <int> <int> <int>
#1 1 4000 2 6 9 NA NA NA
#2 1 7000 7 6 7 8 9 10
或使用data.table
library(data.table)
dcast(setDT(df2)[, n := .N, .(Col1, Col2)][,
head(.SD, 5), .(Col1, Col2)], Col1 + Col2 + n ~
factor(paste0("NewCol", rowid(Col1, Col2)),
levels = paste0("NewCol", 1:5)), value.var = 'Col4')
# Col1 Col2 n NewCol1 NewCol2 NewCol3 NewCol4 NewCol5
#1: 1 4000 2 6 9 NA NA NA
#2: 1 7000 7 6 7 8 9 10
数据
df1 <- structure(list(Col1 = c(1L, 1L, 1L), Col2 = c(7000L, 7000L, 4000L
), Col3 = c(73L, 73L, 117L), Col4 = c(6L, 7L, 6L)),
class = "data.frame", row.names = c(NA,
-3L))
df2 <- structure(list(Col1 = c(1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L),
Col2 = c(7000L, 7000L, 7000L, 7000L, 7000L, 7000L, 7000L,
4000L, 4000L), Col3 = c(73L, 73L, 73L, 73L, 73L, 73L, 73L,
117L, 117L), Col4 = c(6L, 7L, 8L, 9L, 10L, 11L, 12L, 6L,
9L)), class = "data.frame", row.names = c(NA, -9L))