我想要一个这样的数据集:
dat <- data.frame(pos = 1:120, state = c(rep("state1", 30), rep("state2",30), rep("state3",30), rep("state1", 30)))
并将其折叠为以下形式:
dat2 <- data.frame(start = seq(1,120,30), end = seq(30,120,30), state = c("state1","state2","state3","state1"))
总而言之,我想知道每种类别在数据中的开始和结束。
答案 0 :(得分:0)
您可以为此使用dplyr中的group_by
。代码如下:
require(dplyr)
dat1 = dat %>%
dplyr::arrange(state,pos) %>%
dplyr::mutate(occurence=0)
occurence = 0
for(i in 1:nrow(dat1)){
if((i != 1) && ((dat1$pos[i] - dat1$pos[i-1])>1)){
occurence = occurence + 1
}
dat1$occurence[i] = occurence
}
dat2 = dat1 %>%
dplyr::group_by(state,occurence) %>%
dplyr::summarise(start = min(pos,na.rm=T),
end = max(pos,na.rm=T)) %>%
dplyr::arrange(start)
让我知道它是否有效。
输出
# A tibble: 4 x 4
# Groups: state [3]
state occurence start end
<fct> <dbl> <int> <int>
1 state1 0 1 30
2 state2 1 31 60
3 state3 1 61 90
4 state1 1 91 120
您可以根据需要删除“出现次数”列。使用:
dat2 = dat2 %>% dplyr::select(-occurence)
答案 1 :(得分:0)
使用基数R,您可以使用rle
:
with( rle(as.character(dat$state)),
data.frame(state=values,end = cumsum(head(lengths))->end,start = c(1,head(end,-1)+1)))
state end start
1 state1 30 1
2 state2 60 31
3 state3 90 61
4 state1 120 91