Element of vector to different columns of data frame

Viewed 116

I have a df:

   group number id
1      A   abcd  1
2      A   abcd  2
3      A   abcd  3
4      A   efgh  4
5      A   efgh  5
6      B   abcd  1
7      B   abcd  2
8      B   abcd  3
9      B   abcd  9
10     B   ijkl 10

I want to make it like this:

   group number  data1 data2 data3 data4           Length
1      A   abcd      1     2     3                      3
2      A   efgh      4     5                            2
3      B   abcd      1     2     3     9                4
4      B   ijkl      10                                 1

I am sorry I can only make it to df2 like this:

   group number     data               Length
1      A   abcd  c(1,2,3)                   3
2      A   efgh  c(4,5)                     2
3      B   abcd  c(1,2,3,9)                 4
4      B   ijkl  10                         1

My code is here:

library(tidyverse)

df <- data.frame (group = c(rep('A',5),rep("B",5)),
                  number = c(rep('abcd',3),rep('efgh',2),rep('abcd',4),rep('ijkl',1)),
                  id = c(1,2,3,4,5,1,2,3,9,10))

df2 <- df %>%
  group_by(group,number) %>%
  nest() %>%
  mutate(data=map(data,~unlist(.x, recursive = TRUE, use.names = FALSE)),
         Length= map(data, ~length(.x)))

Please feel free to start with df or df2, with(out) any package is fine.

5 Answers
Related