使用rle()查找给定值的最大游程的索引位置

时间:2018-11-12 15:46:15

标签: r indexing

earlier question中,有人发布了答案:

set.seed(100)
coins <- sample(c("H", "T"), 1000, replace = TRUE)
rle_coins <- rle(coins)
max(rle_coins$lengths[rle_coins$values == "H"])

我想知道,根据以上回答,我如何才能发现首长一度的Heads的指数位置?

2 个答案:

答案 0 :(得分:0)

set.seed(100)
coins <- sample(c("H", "T"), 1000, replace = TRUE)


rle_coins <- rle(coins)


##Create a data frame with information
##Index start refers to the index where the run starts
k <- tibble(value = rle_coins$values,
       streak = rle_coins$lengths) %>%
  mutate(index_start = c(1, rep(0,length(rle_coins$lengths)-1)))

#For loop to mutate the index_start variable
for(i in 2:nrow(k)){
    k$index_start[i] <- k$index_start[i-1] + k$streak[i-1]
}
remove(i)

##Filtering the data frame to obtain the largest run
k %>% group_by(value) %>% top_n(1,streak) %>% filter(value == "H")

答案 1 :(得分:0)

grep("H", rle_coins$values)[which.max(rle_coins$lengths[rle_coins$values=="H"])]