本文介绍了按组分组的完整时间序列的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我有一个数据框
dat <- data.frame(c("G", "G", "G", "G"), c("G1", "G1", "G2", "G2"), c('2017-01-01', '2017-01-03', '2017-04-02', '2017-04-05'))
colnames(dat) <- c('Country', 'Place', 'date')
我希望得到以下输出:(每个(国家/地区)组的完整日期)
I would like to have this output: (complete date for each (country-place) group)
dat <- data.frame(c("G", "G", "G", "G", "G", "G", "G"),
c("G1","G1", "G1", "G2", "G2", "G2", "G2"),
c('2017-01-01', '2017-01-03','2017-01-03',
'2017-04-02', '2017-04-03', '2017-04-04', '2017-04-05'))
我尝试过:
dat = dat %>% group_by(Country, Place) %>% complete(date)
但是它不起作用.有人可以帮我吗?
but it does not work.Can anyone help me with this?
推荐答案
您可以这样做:
dat %>%
mutate(date = as.Date(date)) %>%
group_by(Country, Place) %>%
complete(date = seq.Date(min(date), max(date) , by= "day"))
# A tibble: 7 x 3
# Groups: Country, Place [2]
Country Place date
<fct> <fct> <date>
1 G G1 2017-01-01
2 G G1 2017-01-02
3 G G1 2017-01-03
4 G G2 2017-04-02
5 G G2 2017-04-03
6 G G2 2017-04-04
7 G G2 2017-04-05
这篇关于按组分组的完整时间序列的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!