-1

I would like to add a date column to a data frame. The date column needs to populate automatically for the full length of the column. See example below:

enter image description here

Data frame:

df = structure(list(Name = c("Joe", "Sanj", "Rob"), 
                    Col1 = c(20, 60, 40), 
                    Col2 = c(100, 233, 500)),  
               row.names = c(NA, -3L), 
               class = c("tbl_df", "tbl", "data.frame"))

2 Answers2

0

You can add Sys.Date() (todays date) as a new column.

df$Date <- Sys.Date()

# A tibble: 3 x 4
#  Name   Col1  Col2 Date      
#  <chr> <dbl> <dbl> <date>    
#1 Joe      20   100 2020-08-12
#2 Sanj     60   233 2020-08-12
#3 Rob      40   500 2020-08-12
Ronak Shah
  • 377,200
  • 20
  • 156
  • 213
0

The simplest way to do this is by doing the following:

df$date <- as.Date("2020-08-12")

This assigns the data value "2020-08-12" to a new column in df called date. When assigning a length 1 vector to a new column of a dataframe, R will recycle to the same length as the columns in your dataframe (3 in this case). We wrap your date ("2020-08-21") in as.Date() so the column class is "date". If we do not do this, the class will be "character".

Rory
  • 26
  • 3