我可以创建for循环将日历日期划分为R中的唯一星期吗?

我有一个日期列表(mm / dd / yyyy)和相关的星期几,其中每个日期代表对事件的观察(请参见下文)。

Date        DOTW
1/2/2019    Wednesday
1/5/2019    Saturday
1/15/2019   Tuesday
1/17/2019   Thursday
1/22/2019   Tuesday
1/25/2019   Friday
1/25/2019   Friday
2/4/2019    Monday
2/7/2019    Thursday

我想创建一个以星期天(x轴)和y轴观察数(日期在列表中出现的次数)开头的星期几的图。该图将以多行结尾,在日期范围内,每个唯一的星期对应一行。

我相信我需要创建一个for循环来循环显示星期,但是我不确定保持每周分隔的最佳方法,而无需手动创建星期数的第三列。

I have looked up other similar posts (How to divide db dates into weeks?, Convert dates into weeks, etc.) but have not found an answer for this specific question. I have also read through the features of the lubridate package but again, not sure it will meet these specific needs.

谢谢!

评论
纯情小火鸡
纯情小火鸡

我知道这不是折线图,但是使用稀疏数据提供的折线图无需添加更多列即可进行更多工作(就像您说的那样,要避免)。

library(ggplot2)
ggplot(dat, aes(DOTW)) +
  geom_histogram(stat = "count") +
  facet_grid(format(Date, format = "%V") ~ .)
# Warning: Ignoring unknown parameters: binwidth, bins, pad

See my data below on how I ensure the days of the week are ordered correctly. I'm not sure if skipping week numbers is a problem. (This is week-of-year, so if you plan on having different years, perhaps a little more would be appropriate, such as format="%Y-%B".)

by-week faceting of by-date counts

数据:

dat <- read.table(header = TRUE, stringsAsFactors = FALSE, text = "
Date        DOTW
1/2/2019    Wednesday
1/5/2019    Saturday
1/15/2019   Tuesday
1/17/2019   Thursday
1/22/2019   Tuesday
1/25/2019   Friday
1/25/2019   Friday
2/4/2019    Monday
2/7/2019    Thursday")

dat$Date <- as.Date(dat$Date, format = "%m/%d/%Y")
days <- Sys.Date() + 0:6
dat$DOTW <- factor(dat$DOTW, levels = format(days, format = "%A")[order(format(days, format = "%w"))])

If you prefer Monday-based weeks, replace "%w" with "%u".

点赞
评论
墨oo
墨oo

不确定这是否是您要的...

组成大量数据,因为您提供的样本会使您难以解释的折线图很难理解。

library(lubridate)
library(dplyr)
library(ggplot2)


set.seed(123)

day_start <- "2019/01/01"
day_end <- "2019/01/31"

day_seq <- seq(as.Date(day_start), as.Date(day_end), by = "day")

df <-  
  data.frame(Date = sample(day_seq, 500, replace = TRUE)) %>% 
  mutate(Wk = week(Date),
         Dy = wday(Date, label = TRUE,  week_start = getOption("lubridate.week.start", 7))) %>% 
  group_by(Wk, Dy) %>% 
  summarise(Count = n())

ggplot(df, aes(Dy, Count, group = factor(Wk), colour = factor(Wk)))+
  geom_line()

Created on 2020-05-17 by the reprex package (v0.3.0)

点赞
评论