首页 > 解决方案 > 根据存在将行分散到列中。

问题描述

给出以下数据:

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

也许与传播?

标签: r

解决方案


我们可以使用tiudyverse. count获取按“位置”、“天”、“类型”和spread“宽”格式分组的频率

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 R选项aggregatereshape

reshape(aggregate(val ~ ., transform(dat, val = 1), length), 
    idvar = c('location', 'day'), direction = 'wide', timevar = 'type')

推荐阅读