包含客户和购买的数据框
id name department
1 joe fruit
2 peter meat
3 joe warehouse
4 marge fruit
5 marge meat
6 joe pharmacy
我需要这样一个数据框,以这种方式为客户的每一次碰巧放一行:
joe fruit joe warehouse
joe fruit joe pharmacy
peter meat
marge fruit marge meat
针对每个客户。
尝试过dplyr :: join并合并,但无济于事
答案 0 :(得分:2)
怎么样:
full_join(
df %>% group_by(name) %>% slice(1),
df %>% group_by(name) %>% slice(-1),
'name'
)
礼物:
# A tibble: 4 x 5 # Groups: name [?] id.x name department.x id.y department.y <int> <chr> <chr> <int> <chr> 1 1 joe fruit 3 warehouse 2 1 joe fruit 6 pharmacy 3 4 marge fruit 5 meat 4 2 peter meat NA NA
或者简单地
df2 <- df %>% group_by(name) %>% select(-id)
full_join(slice(df2, 1), slice(df2, -1), 'name')
# A tibble: 4 x 3 # Groups: name [?] name department.x department.y <chr> <chr> <chr> 1 joe fruit warehouse 2 joe fruit pharmacy 3 marge fruit meat 4 peter meat NA