1

I would like to add news columns by count of each group in type. My dataframe is like this:

#   color  type  
#   black chair       
#   black chair   
#   black sofa 
#   pink  plate
#   pink  chair
#   red   sofa    
#   red   plate   

I am looking for something like:

#   color  chair sofa plate 
#   black    2     1   0
#   pink     1     0   1
#   red      0     1   1

I used table(df$color, df$type), but the result has no name for column 'color'

Vinícius Félix
  • 8,448
  • 6
  • 16
  • 32

1 Answers1

-1

We may use table from base R

table(df)

Or with pivot_wider

library(tidyr)
pivot_wider(df, names_from = type, values_from = type, 
       values_fn = length, values_fill = 0)
# A tibble: 3 × 4
  color chair  sofa plate
  <chr> <int> <int> <int>
1 black     2     1     0
2 pink      1     0     1
3 red       0     1     1

Or with dcast

library(data.table)
dcast(setDT(df), color ~ type, value.var = 'type', length, fill = 0)

data

df <- structure(list(color = c("black", "black", "black", "pink", "pink", 
"red", "red"), type = c("chair", "chair", "sofa", "plate", "chair", 
"sofa", "plate")), class = "data.frame", row.names = c(NA, -7L
))
akrun
  • 874,273
  • 37
  • 540
  • 662