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
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.
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.
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.
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...
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
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]
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With