Sander Van der Zeeuw
Sander Van der Zeeuw

Reputation: 1092

Group row of values based on a single ID in R

Hi I have a dataframe like this:

> 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")

What i want to is to group on column sku and next to sku should be the eans Belonging to that SKU.

Example:

Row1:

HOU394386-411    8718476625642    8718476625659    8718476625666 8718476625673    8718476625680

Row2:

HOU454800-463    8718476630066    8718476630073    8718476630080 8718476630097    8718476630103

If i try to achieve this with group_by and summarise from the dplyr package or with reshapes function cast i do not get what i want. All EANS become columns and i only want to EANs that belong to a SKU. Is this even possible?

Upvotes: 0

Views: 81

Answers (1)

Roman
Roman

Reputation: 17648

You can try

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

Upvotes: 1

Related Questions