在R dplyr中按计数传播列

时间:2016-11-06 20:23:48

标签: r dataframe dplyr spread

我有一个因子列。我想为每个因素分成一列,然后按每个id显示的因子计数填补空白。假设我们有:

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)

并获得:

   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

我想要这个:

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

我尝试使用dplyr,但我并没有真正使用它,所以它不起作用。

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

我会感谢任何帮助。

2 个答案:

答案 0 :(得分:8)

使用reshape2

library(reshape2)

dcast(car_type, car ~ type)

如果您要使用dplyr,则代码为:

dplyrreshape2

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

dplyrtidyr

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

在任何一种情况下,count(car, type)都相当于

group_by(car, type) %>% tally

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

使用data.table

library(data.table)

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

答案 1 :(得分:5)

在基础R中尝试:

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)