0

I am trying to find a way to transpose only 1 column in my R data frame.

This is the original data frame:

Fruits  Name  Count
Apple   Tom   2
Apple   Bob   2
Banana  Tom   1

This is what I want my data frame to be:

Name  Apple Banana
Tom   2     1
Bob   2     0

Please advice and thanks in advance!

Z.Lin
  • 28,055
  • 6
  • 54
  • 94
MAMS
  • 419
  • 1
  • 6
  • 17
  • Do you want to [reshape from long to wide](http://www.cookbook-r.com/Manipulating_data/Converting_data_between_wide_and_long_format/)? If so, [here is another SO post of interest](https://stackoverflow.com/questions/5890584/how-to-reshape-data-from-long-to-wide-format). – niko May 15 '19 at 21:36
  • 2
    Try this `library(tidyverse); df %>% spread(Fruits, Count)` – Jilber Urbina May 15 '19 at 21:40

2 Answers2

3
library(dplyr)
library(tidyr)
df <- data.frame(Fruits = c("Apple", "Apple", "Banana"),
                 Name = c("Tom", "Bob", "Tom"),
                 Count = c(2,2,1))
df
> df
  Fruits Name Count
1  Apple  Tom     2
2  Apple  Bob     2
3 Banana  Tom     1
df2 <- df %>% 
  tidyr::spread(key = Fruits, value = Count) %>% 
  replace(is.na(.), 0) %>% 
  dplyr::arrange(desc(Name))
df2
> df2
  Name Apple Banana
1  Tom     2      1
2  Bob     2      0
bbiasi
  • 1,549
  • 2
  • 15
  • 31
2

Using @bbiasi data:

tidyr::spread(df2, Fruits, Count, fill = 0)

#  Name Apple Banana
#1  Bob     2      0
#2  Tom     2      1

upd: haven't seen @Jilber Urbina comment, before I posted this

utubun
  • 4,400
  • 1
  • 14
  • 17