[英]R: df from days to weeks
我每天都有一個帶有值(網站瀏覽量)的 df。 但是,我想將這些轉換為每周視圖,因此聚合每周的值,同時保留我的日期列的日期格式。
新的日期列可以是周數。 或者,可以在每個星期日的日期聚合一周(周一至周日)的值。 我嘗試了以下方法,但在這里我丟失了日期格式:
Views %>% group_by(week = week(date)) %>% summarise(value = sum(value))
我在這里嘗試了其他幾個主題,但無法重現任何建議的解決方案。 這真的有那么難嗎? 或者是我嗎? ;)
這是我正在使用的 df 的一部分:
structure(list(date = structure(c(17591, 17592, 17593, 17594,
17595, 17596, 17597, 17598, 17599, 17600, 17601, 17602, 17603,
17604, 17605, 17606, 17607, 17608, 17609, 17610, 17611, 17612,
17613, 17614, 17615, 17616, 17617, 17618, 17619, 17620, 17621,
17622, 17623, 17624, 17625, 17626, 17627, 17628, 17629, 17630,
17631, 17632, 17633, 17634, 17635, 17636, 17637, 17638, 17639,
17640, 17641, 17642, 17643, 17644, 17645, 17646, 17647, 17648,
17649, 17650), class = "Date"), UPV = c(69L, 96L, 35L, 37L, 211L,
128L, 106L, 140L, 84L, 29L, 58L, 125L, 117L, 129L, 160L, 91L,
41L, 33L, 131L, 172L, 130L, 118L, 91L, 19L, 43L, 136L, 165L,
142L, 84L, 86L, 22L, 26L, 49L, 191L, 164L, 147L, 104L, 24L, 34L,
92L, 122L, 125L, 109L, 139L, 23L, 39L, 175L, 140L, 104L, 94L,
62L, 31L, 35L, 155L, 122L, 99L, 68L, 11L, 26L, 44L)), row.names = c(NA,
60L), class = "data.frame")
希望這很清楚! 提前致謝。
也許您正在從dplyr
尋找mutate()
,它會保留您的日期:
library(dplyr)
library(lubridate)
#Code
Views %>% group_by(week = week(date)) %>% mutate(value = sum(UPV))
輸出:
# A tibble: 60 x 4
# Groups: week [9]
date UPV week value
<date> <int> <dbl> <int>
1 2018-03-01 69 9 237
2 2018-03-02 96 9 237
3 2018-03-03 35 9 237
4 2018-03-04 37 9 237
5 2018-03-05 211 10 756
6 2018-03-06 128 10 756
7 2018-03-07 106 10 756
8 2018-03-08 140 10 756
9 2018-03-09 84 10 756
10 2018-03-10 29 10 756
# ... with 50 more rows
更新:使用@alex_jwb90 建議的下一個代碼:
Views %>% group_by(week = week(date)) %>%
summarise(date=max(date),value = sum(UPV)) %>%
ggplot(aes(date, value))+geom_col()
你得到這個輸出:
更新 2:
正確探索數據后,下一個代碼可能很有用:
#Data
df2 <- df %>% mutate(Var=format(date,'%Y-%m')) %>%
group_by(Var) %>%
summarise(Value=sum(value))
#Plot
ggplot(df2,aes(x=factor(Var),y=Value))+
geom_bar(stat = 'identity')+
theme(axis.text.x = element_text(angle=90))
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.