R - 根据连续行和因子水平构建唯一组



通常,只要它们来自数据框中的连续行,我如何根据相同的因子进行分组?例如,我希望下面有test所需的good_output

test <- data.frame(time = 1:10, letter = c("a","a","a","b","a","a","a","b","b","b"))
bad_output <- test %>% group_by(letter) %>% summarize(mean_time = mean(time))
bad_output
# A tibble: 2 x 2
letter mean_time
<fct>      <dbl>
1 a           4   
2 b           7.75
good_output <- data.frame(letter=c("a","b","a","b"), id=c(1,1,2,2), mean_time=c(2,4,6,9))
good_output
letter id mean_time
1      a  1         2
2      b  1         4
3      a  2         6
4      b  2         9

我们可以在"字母"上做一个分组,在"字母"上做一个组(rleiddata.table开始),summarise得到"时间"的mean,用row_number()创建序列列并选择"grp"列

library(dplyr)
library(data.table)
test %>% 
group_by(letter, grp = rleid(letter))  %>%
summarise(mean_time = mean(time)) %>%       
mutate(id = row_number()) %>%
ungroup %>%
select(-grp)
# A tibble: 4 x 3
#  letter mean_time    id
#  <fct>      <dbl> <int>
#1 a              2     1
#2 a              6     2
#3 b              4     1
#4 b              9     2

相关内容

  • 没有找到相关文章

最新更新