简体   繁体   中英

How to convert time variable into numeric variable in R

I have got a date formatted file that contains date format column in the following format

4\8    # April 8th, 2013
7\12   # July 12th, 2013

All these dates are default in 2013, Now I want to create a column that specify the number of days since 4\\1\\2013 (April 1st, 2013), for April 8th, it is 8.

How should I proceed? I should use fill in 2013 as prefix then use as.Date function in R? But then it seems I should replace "\\" by "/"

OK, I want to summarize @rawr's solution so that others can follow

First, I need to change from "\\" to "//" for reading format requirement by R

Second, I need append 2013 to the end of string, the trick here is to execute paste0(dates, "\\\\") first (I figured out this myself! ) before executing dates <- paste0(dates, '\\\\2013') to ensure there are two "\\" before 2013, otherwise there will be always just one escape symbol before 2013.

Third, execute as.Date("6\\\\\\\\4\\\\\\\\2013", format = '%m\\\\\\\\%d\\\\\\\\%Y') , or something like this.

\\ is an escape character, so R won't like 4\\8 , so you need to use \\\\ for a single \\

> cat('\\')
\

here is one way to do it:

dates
# [1] "4\\8"  "7\\12"
dates <- paste0(dates, '\\2013')
# [1] "4\\8\\2013"  "7\\12\\2013"
as.Date(dates, format = '%m\\%d\\%Y') - as.Date('2013-04-01') + 1
# Time differences in days
# [1]   8 103
as.numeric(as.Date(dates, format = '%m\\%d\\%Y') - as.Date('2013-04-01') + 1)
# [1]   8 103

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