嗨,我有一个像这样的数据框:
> dput(tst_df)
structure(list(Item = c("a", "a", "a", "a", "a", "b", "b", "b",
"b", "b"), sku = structure(c(1L, 1L, 1L, 1L, 1L, 2L, 2L, 2L,
2L, 2L), .Label = c("HOU394386-411", "HOU454800-463"), class = "factor"),
ean = structure(1:10, .Label = c("8718476625642", "8718476625659",
"8718476625666", "8718476625673", "8718476625680", "8718476630066",
"8718476630073", "8718476630080", "8718476630097", "8718476630103"
), class = "factor")), .Names = c("Item", "sku", "ean"), row.names = c(NA,
-10L), class = "data.frame")
我要在sku列上分组并在sku旁边是属于该SKU的eans。
示例:
第1行:
HOU394386-411 8718476625642 8718476625659 8718476625666 8718476625673 8718476625680
第2行:
HOU454800-463 8718476630066 8718476630073 8718476630080 8718476630097 8718476630103
如果我尝试使用group_by并从dplyr包中进行总结或使用reshapes函数强制转换,我将无法获得所需的内容。所有的EANS都成为列,我只希望属于SKU的EAN。这有可能吗?
答案 0 :(得分:1)
您可以尝试
library(tidyverse)
d %>%
group_by(sku) %>%
mutate(n=1:n()) %>%
select(-Item) %>%
ungroup() %>%
spread(n, ean)
# A tibble: 2 x 6
sku `1` `2` `3` `4` `5`
<fct> <fct> <fct> <fct> <fct> <fct>
1 HOU394386-411 8718476625642 8718476625659 8718476625666 8718476625673 8718476625680
2 HOU454800-463 8718476630066 8718476630073 8718476630080 8718476630097 8718476630103