3

I think I am about to lose my mind!

I need to create a data frame of dates with a column name but I am struggling to figure it out.

I know I can assign the colnames outside of the dplyr chain using colnames(date_df) <- "DATE" but for my own learning I would like to understand if it's possible to do within the dplyr pipe/chain

library(tidyverse)
library(lubridate)

    date_df <- seq.Date(from = as.Date(today()- days(7)),
                        to = as.Date(today()),
                        by = "day") %>% 
      as.data.frame(col.names = c("DATE"))

Can someone please put me out of my misery and help me add a column name to this basic problem?

3
  • 2
    Maybe simply: data.frame(DATE = seq.Date(from = as.Date(today()- days(7)), to = as.Date(today()), by = "day")) Commented Apr 30, 2021 at 9:40
  • @zx8754 thank you, sometimes I feel like I'm going backwards in my familiarity with R. I feel like a jackass. Commented Apr 30, 2021 at 9:43
  • Posted as answer, sometimes we overcomplicate things, back to basics :) Commented Apr 30, 2021 at 9:49

2 Answers 2

4

There are lot of ways to do that, since you used data.frame :

library(lubridate)
library(magrittr)

seq.Date(from = as.Date(today()- days(7)),
        to = as.Date(today()),
        by = "day")  %>%
  data.frame(DATE = .)

#        DATE
#1 2021-04-23
#2 2021-04-24
#3 2021-04-25
#4 2021-04-26
#5 2021-04-27
#6 2021-04-28
#7 2021-04-29
#8 2021-04-30
Sign up to request clarification or add additional context in comments.

4 Comments

Why call seq.Date directly rather than via seq?
I just copied it from OP's attempt. Although curious any drawbacks with that?
@KonradRudolph probably, (like myself) copy pasted OP's code, which is not related to the problem anyway, but yes seq works fine, too.
@Ronak Ah, hadn’t noticed that. The predominant drawback is that it’s more code, and the added code is irrelevant: it doesn’t provide any informative detail. Furthermore, it makes the code non-generic; but of course this makes absolutely no difference in this specific code (but it makes it slightly harder to refactor into a reusable module later on). Nevertheless, I find it a good rule of thumb to keep code as generic as possible. Often this leads to cleaner algorithms and drastically increases reusability (and, thus, reuse).
3

Maybe simply:

data.frame(DATE = seq.Date(from = as.Date(today() - days(7)), 
                           to = as.Date(today()),
                           by = "day"))

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.