pivot_wider
library(dplyr)
library(tidyr)
df1 %>%
pivot_wider(names_from = c(segment), values_from = c(count, freq))
# A tibble: 2 x 7
# id count_a count_b count_c freq_a freq_b freq_c
# <int> <chr> <chr> <chr> <chr> <chr> <chr>
#1 1 x1a x1b x1c f1a f1b f1c
#2 2 x2a x2b x2c f2a f2b f2c
或与
dcast
library(data.table)
dcast(setDT(df1), id ~ segment, value.var = c('count', 'freq'))
# id count_a count_b count_c freq_a freq_b freq_c
#1: 1 x1a x1b x1c f1a f1b f1c
#2: 2 x2a x2b x2c f2a f2b f2c
更新
如果存在重复项,则创建序列列
df1 %>%
mutate(rn = rowid(segment)) %>%
pivot_wider(names_from = c(segment), values_from = c(count, freq)) %>%
select(-rn)
data.table
dcast(setDT(df1), id + rowid(segment) ~ segment,
alue.var = c('count', 'freq'))[, segment := NULL][]
数据
df1 <- structure(list(id = c(1L, 1L, 1L, 2L, 2L, 2L), segment = c("a",
"b", "c", "a", "b", "c"), count = c("x1a", "x1b", "x1c", "x2a",
"x2b", "x2c"), freq = c("f1a", "f1b", "f1c", "f2a", "f2b", "f2c"
)), class = "data.frame", row.names = c(NA, -6L))