简体   繁体   中英

Create an r data.table with a date formatted column

I'm trying to create a data.table with a date/time formatted column to be populated in the next steps. I've tried a bunch of different functions but I just can't find the one the package wants.

See column3 in the below examples:

require(data.table)
num_rows <- 5
dt <- data.table(column1 = character(num_rows),
                 column2 = integer(num_rows),
                 column3 = date(num_rows)
                 )

dt <- data.table(column1 = character(num_rows),
                 column2 = integer(num_rows),
                 column3 = POSIXct(num_rows)
                 )

dt <- data.table(column1 = character(num_rows),
                 column2 = integer(num_rows),
                 column3 = IDateTime(num_rows)
                 )

What is the function that creates a date or time column in data.table? I can't find it anywhere.

Cheers.

Note that integer(num_rows) makes a vector of 0s, character(num_rows) makes a vector of "" s etc.

So you just initialise your dates to some value, eg

column3=rep(Sys.time(), num_rows) # POSIXct

or

column3=rep(Sys.Date(), 3) # Date

I'd recommend initialising it to some default date/datetime that makes sense for your application (eg your column2 is initialised to 0 and your column1 is initialised to "" ). Maybe some default origin value eg 1970-01-01 00:00 ( column3=rep(as.POSIXct('1970-01-01 00:00'), num_rows) )

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM