0

I have a dataframe with several rows that have the same ID number and a column with character values in each row, that I want to split into separate columns.

I want to go from something like this:

id <- rep(1:5, each = 5)
source <- rep(c("One", "Two", "Three", "Four", "Five"), times = 5)  
dat_long <- cbind(id, source)

To something like this:

id2 <- rep(1:5)

ess1 <- rep(c("One"), each = 5)
ess2 <-  rep(c("Two"), each = 5)
ess3 <- rep(c("Three"), each = 5)
ess4 <- rep(c("Four"), each = 5)
ess5 <-  rep(c("Five"), each = 5)

dat_wide <- cbind(id2, ess1, ess2, ess3, ess4, ess5)

I've tried pivot_wider, reshape, separate but haven't found a way of doing what I want to do.

Con Des
  • 359
  • 1
  • 2
  • 9
  • 1
    `dat_long %>% group_by(id) %>% mutate(row = row_number()) %>% pivot_wider(names_from = row, values_from = source)` where `dat_long <- data.frame(id, source)` – Ronak Shah Aug 31 '20 at 06:31
  • This kind of works! I end up with a bunch of extra columns but can get rid of those. – Con Des Aug 31 '20 at 06:53

1 Answers1

1

This would get you 90 % there.

library(tidyr)

pivot_wider(as.data.frame(dat_long),
            id_cols = id,
            names_from = source,
            values_from = source)

# A tibble: 5 x 6
  id    One   Two   Three Four  Five 
  <fct> <fct> <fct> <fct> <fct> <fct>
1 1     One   Two   Three Four  Five 
2 2     One   Two   Three Four  Five 
3 3     One   Two   Three Four  Five 
4 4     One   Two   Three Four  Five 
5 5     One   Two   Three Four  Five 
Roman Luštrik
  • 69,533
  • 24
  • 154
  • 197