0

I have a data frame that looks this.

df <- data.frame(names = c("Ram","Siddhharth","Nithin","Aashrit","Bragadish","Sridhar"),
                 house = c("A", "B", "A", "B", "A", "B"))

I want to create a new data frame which gets re-arranged based on the house they are in.

Expected Output

house_A   house_B
1 Ram       Siddhharth
2 Nithin    Aashrit
3 Bragadish Sridhar 

How can I achieve this? Many thanks in advance.

Sri Sreshtan
  • 535
  • 3
  • 12
  • 1
    You can use `df %>% group_by(house) %>% mutate(row = row_number()) %>% pivot_wider(names_from = house, values_from = names, names_prefix = 'house_')` . This link has other options : https://stackoverflow.com/questions/11322801/transpose-reshape-dataframe-without-timevar-from-long-to-wide-format – Ronak Shah Jun 28 '20 at 16:26
  • Does this answer your question? [R Reshape data frame from long to wide format?](https://stackoverflow.com/questions/50765323/r-reshape-data-frame-from-long-to-wide-format) – Jan Jun 28 '20 at 16:53

1 Answers1

3

You could use tidyr:

df %>%
  pivot_wider(names_from="house", names_prefix="house_", values_from="names", values_fn=list) %>%
  unnest(cols=everything())

This returns

# A tibble: 3 x 2
  house_A   house_B   
  <chr>     <chr>     
1 Ram       Siddhharth
2 Nithin    Aashrit   
3 Bragadish Sridhar  
Martin Gal
  • 16,640
  • 5
  • 21
  • 39