user3519324
user3519324

Reputation: 355

Create Date from this format:YYYYddmm in R

I have trouble with date formats. My input data looks like:

73;2013120101;   7;  38;   0.1;  99.0;eor

Second column 2013120101 is my date column. I want to import it to work on it in R and eventually it should look like

1969 01 02 00:00

This way

 dwd <- read.csv(file="testdwd.txt",header=T,sep=";",stringsAsFactors=F)
 dwd[,1] <- ymd(dwd[,1])

yields 1982-12-01 but I don't know how to get the rest done.

Upvotes: 1

Views: 118

Answers (3)

Mamoun Benghezal
Mamoun Benghezal

Reputation: 5314

you can try strptime and format, example

d <- "2013120121"
x <- strptime(x=d, format = "%Y%m%d%H")
format(x, "%Y %m %d %k:%M")
## [1] "2013 12 01 21:00" # which gives the desired output

%Yfor year, %m for month, %d for day, %k for hour and %M for minutes.

Upvotes: 3

zx8754
zx8754

Reputation: 56219

Using lubridate

require("lubridate")

#dummy data
x <- read.table(text="73;2013120101;   7;  38;   0.1;  99.0;eor",sep=";")

#reformat
ymd_hms(paste0(x$V2,"0000"))

#output
#[1] "2013-12-01 01:00:00 UTC"

Upvotes: 1

plannapus
plannapus

Reputation: 18759

The base function strptime handles it correctly:

> dwd <- read.csv(textConnection("73;2013120101;   7;  38;   0.1;  99.0;eor"),
                  sep=";",stringsAsFactors=F,head=F)
> strptime(dwd[2],"%Y%m%d%H")
                   V2 
"2013-12-01 01:00:00" 

Upvotes: 1

Related Questions