week-dates in R [duplicate] - r

This question already has answers here:
Transform year/week to date object
(2 answers)
Closed 4 years ago.
In R, how do I convert the string 1/2010 (week 1 of 2010) into a Date or POSIXct (or POSIXlt) object?
I tried
as.Date('1/2010', "%W/%Y")
[1] "2010-06-29"
I also tried
strptime('1/2010', "%W/%Y")
[1] "2010-06-29 BRT"
But these are clearly not what I want.
In the end, I guess doesn't really matter which exact is picked, so long as I can correctly re-convert this to "weeks since origin".

library(splitstackshape)
date <- c("1/2013","3/2013")
date = data.frame(date)
df = data.frame(cSplit(date,"date","/"))
colnames(df) = c("week", "year")
df$date = as.Date(paste(df$year, df$week, 1, sep="-"), "%Y-%U-%u")

Related

Convert a date time character string to date - YYYYMM format [duplicate]

This question already has answers here:
converting datetime string to POSIXct date/time format in R
(1 answer)
How to convert string "MMM DD YYYY" to date YYYY-MM-DD
(1 answer)
Closed 7 months ago.
I have a character string date time string but need to convert the same into YYYYMM date format. Cannot seem to find a solution as all functions are converting into NA or weird date format.
Date_format_current <- '02/09/2020 23:35'
You can use the following code
library(lubridate)
library(zoo)
current <- '02/09/2020 23:35'
as.yearmon(dmy_hm(current))
#> [1] "Sep 2020"
#Or
format(dmy_hm(current), "%Y-%m")
#> [1] "2020-09"
#Or
format_ISO8601(dmy_hm(current), precision = "ym")
#> [1] "2020-09"

Covert months represented as integer into dates [duplicate]

This question already has answers here:
Converting year and month ("yyyy-mm" format) to a date?
(9 answers)
Closed 3 years ago.
I am trying to convert months in the following format:
histdata <- c("198001", "198002", "198003")
I tried:
histdata <- transform(histdata, date = as.Date(as.character(date), "%Y%m"))
but then all data turned to NA.
I would like to find a solution that will return a vector of dates instead.
You could try
convert_date <- function(x)
{
x <- as.character(x)
as.POSIXct(paste0(substr(x, 1, 4), "-", substr(x, 5, 6), "-01"))
}
So that you have:
convert_date(c(198002, 198003, 202001))
# [1] "1980-02-01 GMT" "1980-03-01 GMT" "2020-01-01 GMT"
library(readr)
ym <- c("198001", "198002", "198003")
parse_date(ym, format = "%Y%m")
or
library(readr)
ym <- c(198001, 198002, 198003)
parse_date(as.character(ym), format = "%Y%m")
You can use base function as.Date with first day of the month added to your representation of the month:
as.Date(paste0(as.character(201901L), "01"), format = "%Y%m%d")

String format parsing in R [duplicate]

This question already has answers here:
How to convert dd/mm/yy to yyyy-mm-dd in R
(6 answers)
Closed 3 years ago.
When I parse a character string into a date, Why does this not throw an error or an NA? I have tried the following
t <- "31-Oct-2012"
as.Date(t, format = "%d-%B-%Y") # this produces the expected result
as.Date(t, format = "%d-%B-%y") # I was expecting an NA
Instead I get
[1] "2020-10-31"
Because %y is for two digit year, so it takes only first two digits and ignores the rest. It treats t as
as.Date("31-Oct-20", format = "%d-%B-%y")
#[1] "2020-10-31"
This also works when you have anything after 2-digit year. See
as.Date("31-Oct-20ABC", format = "%d-%B-%y")
#[1] "2020-10-31"
R tries to "auto-complete" when there is less information, it returns some (incorrect) date for
as.Date("31-Oct-20", format = "%d-%B-%Y")
#[1] "0020-10-31"
but returns NA for
as.Date("31-Oct-ABC20", format = "%d-%B-%y")
#[1] NA

Add integer to a year in R [duplicate]

I have a date in R, e.g.:
dt = as.Date('2010/03/17')
I would like to subtract 2 years from this date, without worrying about leap years and such issues, getting as.Date('2008-03-17').
How would I do that?
With lubridate
library(lubridate)
ymd("2010/03/17") - years(2)
The easiest thing to do is to convert it into POSIXlt and subtract 2 from the years slot.
> d <- as.POSIXlt(as.Date('2010/03/17'))
> d$year <- d$year-2
> as.Date(d)
[1] "2008-03-17"
See this related question: How to subtract days in R?.
You could use seq:
R> dt = as.Date('2010/03/17')
R> seq(dt, length=2, by="-2 years")[2]
[1] "2008-03-17"
If leap days are to be taken into account then I'd recommend using this lubridate function to subtract months, as other methods will return either March 1st or NA:
> library(lubridate)
> dt %m-% months(12*2)
[1] "2008-03-17"
# Try with leap day
> leapdt <- as.Date('2016/02/29')
> leapdt %m-% months(12*2)
[1] "2014-02-28"
Same answer than the one by rcs but with the possibility to operate it on a vector (to answer to MichaelChirico, I can't comment I don't have enough rep):
R> unlist(lapply(c("2015-12-01", "2016-12-01"),
function(x) { return(as.character(seq(as.Date(x), length=2, by="-1 years")[2])) }))
[1] "2014-12-01" "2015-12-01"
This way seems to do the job as well
dt = as.Date("2010/03/17")
dt-365*2
[1] "2008-03-17"
as.Date("2008/02/29")-365*2
## [1] "2006-03-01"
cur_date <- str_split(as.character(Sys.Date()), pattern = "-")
cur_yr <- cur_date[[1]][1]
cur_month <- cur_date[[1]][2]
cur_day <- cur_date[[1]][3]
new_year <- as.integer(year) - 2
new_date <- paste(new_year, cur_month, cur_day, sep="-")
Using Base R, you can simply use the following without installing any package.
1) Transform your character string to Date format, specifying the input format in the second argument, so R can correctly interpret your date format.
dt = as.Date('2010/03/17',"%Y/%m/%d")
NOTE: If you look now at your enviroment tab you will see dt as variable with the following value "2010-03-17" (Year-month-date separated by "-" not by "/")
2) specify how many years to substract
years_substract=2
3) Use paste() combined with format () to only keep Month and Day and Just substract 2 year from your original date. Format() function will just keep the specific part of your date accordingly with format second argument.
dt_substract_2years<-
as.Date(paste(as.numeric(format(dt,"%Y"))-years_substract,format(dt,"%m"),format(dt,"%d"),sep = "-"))
NOTE1: We used paste() function to concatenate date components and specify separator as "-" (sep = "-")as is the R separator for dates by default.
NOTE2: We also used as.numeric() function to transform year from character to numeric

How to extract the hour of this kind of timestamp? [duplicate]

This question already has an answer here:
Extracting 2 digit hour from POSIXct in R
(1 answer)
Closed 7 years ago.
This is how my timestamp looks like
date1 = timestamp[1]
date1
[1] 07.01.2016 11:52:35
3455 Levels: 01.02.2016 00:11:52 01.02.2016 00:23:35 01.000:30:21 31.01.2016 23:16:18
When I try to extract the hour, I get an invalid 'trim' argument. Thank you !
format(date1, "%I")
Error in format.default(structure(as.character(x), names = names(x), dim = dim(x), :
invalid 'trim' argument
How can I extract single components like the hour from this timestamp.
With base R:
format(strptime(x,format = '%d.%m.%Y %H:%M:%S'), "%H")
[1] "11"
data
x <- as.factor("07.01.2016 11:52:35")
You first need to parse the time
d = strptime(date1,format = '%d.%m.%Y %H:%M:%S')
Then use lubridate to extract parts like hour etc.
library(lubridate)
hour(d)
minute(d)

Resources