Show the count result in new columns

Hi

I have data frame below. I am using group_by and summarize to get the count. However the output is 3 columns with Name, Color, and count.

Name		Color

car		        green
bus		red
train		black
ship		red
bus		red
car		        black	
ship		green
car		        black
bus		black	
train		red
car		        green
bus		green
ship		red
bus		green
train		red

How do I make the output like this?

Name green red black

car 2 0 2
bus 2 2 1
train 0 2 1
ship 1 2 0

Hi,

You could use pivot_wider. Like this...

df <- tribble(~Name, ~Color,
              'car', 'green',
              'bus','red',
              'train','black',
              'ship','red',
              'bus','red',
              'car','black',	
              'ship','green',
              'car','black',
              'bus','black',	
              'train','red',
              'car','green',
              'bus','green',
              'ship', 'red',
              'bus', 'green',
              'train','red')

df %>% 
  count(Name, Color, sort = TRUE) %>% 
  pivot_wider(names_from = Color, values_from = n, values_fill = 0)

Brgds. Henrik

1 Like

This topic was automatically closed 7 days after the last reply. New replies are no longer allowed.

If you have a query related to it or one of the replies, start a new topic and refer back with a link.