r - 在 dplyr 中选择特定行
问题描述
样本数据:
dat <- structure(list(value = c(860L, 860L, 835L, 835L, 870L, 820L, 820L, 850L, 850L, 810L,
852L, 840L, 840L, 825L, 825L, 900L, 900L, 830L,
830L, 865L, 865L, 822L, 822L, 882L, 882L, 867L, 867L, 725L,
725L, 727L, 727L, 874L, 874L),
loc.id = c(12L, 13L, 12L, 13L, 12L, 12L, 13L, 12L, 13L, 12L,
13L, 12L, 13L, 12L, 13L, 12L, 13L, 12L, 13L, 12L, 13L, 12L,
13L, 12L, 13L, 12L, 13L, 12L, 13L, 12L, 13L, 12L, 13L)),
class = "data.frame", row.names = c(NA, -33L))
dat <- dat %>% dplyr::arrange(loc.id, value)
dat <- dat %>% dplyr::group_by(loc.id) %>% dplyr::mutate(length.val = n()) %>% dplyr::mutate(points.l = ceiling(length.val/4))
对于每个 loc.id,我想选择 4 行应该被索引为(使用 loc.id == 12 的示例):
1)第一行是行号,
2)第一行是第一行 + points.l在 loc.12 的情况下是第 6 行,
3) 最后一行 - points.l 在 loc.12 的情况下是第 12 行 (17 - 5)
4) 最后一行是第 17 行。就像是:
dat %>% group_by(loc.id) %>%
dplyr::filter(row_number() == 1st row,
row_number() == 1st row + points.l,
row_number() == last row - points.l,
row_number() == last row)
解决方案
简单地 :
dat %>% group_by(loc.id) %>% filter(row_number() %in% c(1,1+points.l,n()-points.l,n()))
推荐阅读
- sql - SSMS 设计器问题 IIF SQL Server
- java - 在 Java 中覆盖泛型方法的正确方法
- java - 使用JUnit @ResourceLock 顺序执行一些测试类
- java - 无法通过 Java 从数据库中检索记录
- html - 延迟加载期间加载主体不包含父元素
- azure - 具有基于策略的站点到站点连接的同一网络上的 Azure 点到站点 VPN
- android - 列表视图下的按钮
- python - 如何在 Python 中验证 application/x-bzip2 类型的响应
- python - When to start the google cloud profiler in a Django project?
- sql - 选择函数索引或新列索引