根据状态将行分散为列。

时间:2019-01-04 20:35:52

标签: r

提供了以下数据:

location = c("A", "A", "A", "B", "B")
day = c("Mon","Mon","Mon","Tue", "Tue")
type = c("road", "scan", "fly", "road", "fly")

dat <- data.frame(location,day, type) 


location day    type
   A       Mon  road
   A       Mon  scan
   A       Mon  fly
   B       Tue  road
   B       Tue  fly

我需要一种解决方法,使它看起来像这样

location day road scan fly
     A    Mon   1   1   1
     B    Tue   1   0   1

也许传播?

1 个答案:

答案 0 :(得分:2)

我们可以使用tiudyverse。使用countspread将按“位置”,“天”,“类型”分组的频率获取为“宽”格式

library(tidyverse)
dat %>% 
  count(location, day, type) %>% 
  spread(type, n, fill = 0)
# A tibble: 2 x 5
#  location day     fly  road  scan
#  <fct>    <fct> <dbl> <dbl> <dbl>
#1 A        Mon       1     1     1
#2 B        Tue       1     1     0

带有base Raggregate的{​​{1}}选项

reshape