Distribute columns in an account in R dplyr

I have a column of factors. I would like to expand in one column for each coefficient, and then fill in the gaps in the account of this factor for each identifier. Let's pretend that:

car <- c("a","b","b","b","c","c","a","b","b","b","c","c")
type <- c("good", "regular", "bad","good", "regular", "bad","good", "regular", "bad","good", "regular", "bad")
car_type <- data.frame(car,type)

and get:

   car    type
1    a    good
2    b regular
3    b     bad
4    b    good
5    c regular
6    c     bad
7    a    good
8    b regular
9    b     bad
10   b    good
11   c regular
12   c     bad

I want it:

> results
  car good regular bad
1   a    2       0   0
2   b    2       2   2
3   c    0       2   2

I am trying to use this with dplyr, but I actually don't use it, so it does not work.

car_type %>%
  select(car, type) %>%
  group_by(car) %>%
  mutate(seq = unique(type)) %>%
  spread(seq, type)

I would like to thank any help.

+4
source share
2 answers

C reshape2:

library(reshape2)

dcast(car_type, car ~ type)

If you are going to use dplyr, the code will look like this:

dplyr and reshape2

car_type %>% count(car, type) %>%
  dcast(car ~ type, fill=0)

dplyr and tidyr

car_type %>% count(car, type) %>%
  spread(type, n, fill=0)

Anyway count(car, type)equivalent

group_by(car, type) %>% tally

or

group_by(car, type) %>% summarise(n=n())

WITH data.table

library(data.table)

dcast(setDT(car_type), car ~ type, fill=0)
+7
source

Try this in the R database:

xtabs(~car+type, car_type)

#   type
#car bad good regular
#  a   0    2       0
#  b   2    2       2
#  c   2    0       2

OR

table(car_type)
+5

Source: https://habr.com/ru/post/1660009/


All Articles