Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I convert date to number of days in R

Tags:

r

How do I convert date to number of days, starting from the first day of the year.

How do I convert the following to the expected result below?

   Date               
02/01/2000         
20/02/2000         
12/12/2000         
13/01/2001   

Below is expected result.

Date               NumDays  TotalDays
02/01/2000          1          1
20/02/2000          51         51
12/12/2000          346        346
13/01/2001          13         379
like image 366
user18143 Avatar asked Oct 24 '13 11:10

user18143


People also ask

How do I convert a date into a number in R?

To convert Date to Numeric format in R, use the as. POSIXct() function and then you can coerce it to a numeric value using as. numeric() function.

How do you convert a date into a day of the week in R?

Method 2: Using strftime() function. In this method of converting the date of the week, the user needs to call strftime() function which is an in-built function and pass the respected parameters into it, and then in return, the function will give the weekdays of the given date to the user.

How do I change the date format in R studio?

To format = , provide a character string (in quotes) that represents the current date format using the special “strptime” abbreviations below. For example, if your character dates are currently in the format “DD/MM/YYYY”, like “24/04/1968”, then you would use format = "%d/%m/%Y" to convert the values into dates.

How do you convert days into dates?

The DAY function takes just one argument, the date from which you want to extract the day. In the example, the formula is: = DAY ( B5 ) B5 contains a date value for January 5, 2016. The DAY function returns the number 5 representing the day...


2 Answers

Load your dataset

df <- structure(list(Date = structure(c(1L, 4L, 2L, 3L), .Label = c("02/01/2000", 
"12/12/2000", "13/01/2001", "20/02/2000"), class = "factor"), 
    Date2 = structure(c(10958, 11007, 11303, 11335), class = "Date"), 
    NumDays = structure(c(1, 50, 346, 378), units = "days", class = "difftime")), .Names = c("Date", 
"Date2", "NumDays"), row.names = c(NA, -4L), class = "data.frame")

Format dates:

startdate <- as.Date("01/01/2000","%d/%m/%Y")
df$Date2 <-  as.Date(df$Date,"%d/%m/%Y")

Use difftime to calculate the difference in days

df$NumDays  <- difftime(df$Date2,startdate ,units="days")

df

         Date      Date2  NumDays
# 1 02/01/2000 2000-01-02   1 days
# 2 20/02/2000 2000-02-20  50 days
# 3 12/12/2000 2000-12-12 346 days
# 4 13/01/2001 2001-01-13 378 days
like image 181
Jonas Tundo Avatar answered Oct 17 '22 04:10

Jonas Tundo


I guess this will help:

Use as.Date()

Example:

one <- as.Date(c("02/01/2000", "01/01/2000"))

number of days between 02/01/2000 and 02/01/2000:

days <- one[1] - one[2]
like image 37
Vinayak Pahalwan Avatar answered Oct 17 '22 04:10

Vinayak Pahalwan