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
也许与传播?
解决方案
我们可以使用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
选项aggregate
和reshape
reshape(aggregate(val ~ ., transform(dat, val = 1), length),
idvar = c('location', 'day'), direction = 'wide', timevar = 'type')
推荐阅读
- php - PHP PDO ODBC SELECT 返回部分结果
- json - jq 过滤器聚合成对象的属性
- python-3.x - 单独模式中的 Alembic 版本表
- spring-boot - 如何在 Spring Boot 的 websocket 主题中使用选择器发送消息
- java - 努力寻找 R 编程中的下一个素数
- ios - 如何在启用#if canImport() 的情况下添加可选委托?
- html - png 图像作为 html 按钮
- laravel - laravel nova 指标符合过滤表
- css - Rails 中包含的样式表
- python - 按正则表达式和标签组合的 Pandas 过滤器