Convert Yyyymmdd String to Date Class in R

R read dates in format yyyymmdd

Your dates are in number format, so R thinks it represents a timestamp (in such case it needs origin of timestamp, usually 1st January 1970). What you want is comprehension from strings, so you should convert your numbers to characters first:

as.Date(as.character(yield.usd$Fecha), format='%Y%m%d')

Converting character of YYYYmmdd to date in R

Your approach is correct however df$date is numeric so it has lot more decimal places than you actually see. You could round to 2 decimal places and add arbitrary date (01) and convert to date class using appropriate format.

df$date <- as.Date(paste0(round(df$date, 2), '.01'), '%Y.%m.%d')
df$date
#[1] "1947-01-01" "1947-02-01" "1947-03-01" "1947-04-01" "1947-05-01"

Another approach using zoo::as.yearmon class.

df$date <- as.Date(zoo::as.yearmon(as.character(round(df$date,2)), '%Y.%m'))

Change Date format - Convert to Date Class

A Date class is always shown like "2020-08-27" in R. That's R's standard Date. To reformat it into something different you can use strftime. It assumes a Date class and outputs a character object with your desired format, e.g.

df1$date2
[1] "2020-08-27" "2020-08-28" "2020-08-29"

class(df1$date2)
[1] "Date"

strftime(df1$date2, format="%m/%d/%Y")
[1] "08/27/2020" "08/28/2020" "08/29/2020"

class(strftime(df1$date2, format="%m/%d/%Y"))
[1] "character"

Converting YYYYMMDDHHMMSS to a date and time class in r

In Base R:

data.frame(datetime2=as.POSIXct(as.character(df$datetime),
format="%Y%m%d%H%M%S"),
cycle)

Output:

            datetime2 cycle
1 2021-08-30 10:20:55 25
2 2021-08-30 10:23:12 30
3 2021-08-30 10:23:35 35

The key here is as.POSIXct with format:

> as.POSIXct(as.character(df$datetime), format="%Y%m%d%H%M%S")
[1] "2021-08-30 10:20:55 CST" "2021-08-30 10:23:12 CST" "2021-08-30 10:23:35 CST"
>

Convert string to date, format: dd.mm.yyyy

The format is case-sensitive ("%y" is ambiguous and system dependent, I believe):

as.Date(D, "%d.%m.%Y")
[1] "1948-12-06"

The help topic ?strptime has details:

 ‘%y’ Year without century (00-99).  On input, values 00 to 68 are
prefixed by 20 and 69 to 99 by 19 - that is the behaviour
specified by the 2004 and 2008 POSIX standards, but they do
also say ‘it is expected that in a future version the default
century inferred from a 2-digit year will change’.

YYYYMMDD format

You might have better luck with as.Date. If df is the data, then you can do

df$date <- as.Date(as.character(df$date), format = "%Y%m%d")
with(df, plot(date))

Sample Image

How to transform a numeric variable containing a date (YYYYMMDD) into a POSIXct format variable

You can do that pretty easily with lubridate.

library(tidyverse)
library(lubridate)

df1<- data.frame(
date=c(20160801, 20160802, 20160803),
var1=c(4, 56, 76)
)
df1 %>%
mutate(date = ymd(date))


Related Topics



Leave a reply



Submit