我有一个如下数据框。第一列是位置,最后一列是水平。我想输出相邻行中具有相同数字的行范围。任何与' 2'应该被忽略。你能帮忙吗
输入:
1 3
10000 3
20000 3
30000 1
40000 2
50000 2
60000 2
70000 3
80000 1
90000 1
The output
1- 2999 3
3000-3999 1
7000-7999 3
8000-9999 1
答案 0 :(得分:1)
这是使用dplyr
的chaning函数的方法。这是示例数据
dd <- structure(list(pos = c(1L, 10000L, 20000L, 30000L, 40000L, 50000L,
60000L, 70000L, 80000L, 90000L), level = c(3L, 3L, 3L, 1L, 2L,
2L, 2L, 3L, 1L, 1L)), .Names = c("pos", "level"), class = "data.frame",
row.names = c(NA, -10L))
dd <- dd[order(dd$pos), ] #make sure its sorted by position
如果你下一个pos的差异总是10000,你可以
library(dplyr)
dd %>% arrange(pos) %>%
mutate(run=cumsum(c(0,diff(level))!=0)) %>%
subset(level!=2) %>%
group_by(run) %>%
summarise(level=max(level), start=min(pos), end=max(pos)+9999) %>%
select(-run)
# level start end
# 1 3 1 29999
# 2 1 30000 39999
# 3 3 70000 79999
# 4 1 80000 99999
,否则
dd %>% arrange(pos) %>%
mutate(run=cumsum(c(0,diff(level))!=0), nextpos=lead(pos)) %>%
subset(level!=2) %>%
group_by(run) %>%
summarise(level=max(level), start=min(pos), end=max(nextpos)-1) %>%
select(-run)
# level start end
# 1 3 1 29999
# 2 1 30000 39999
# 3 3 70000 79999
# 4 1 80000 NA
除了最后一组之外,可以计算到下一组的距离。