1

I have the various file name as given below: file<-"/path/path/path/pth.0p25.2015011500.p264.path2.pathpathh254004.nc"

Problem 1: I want datetime part(2015011500)from the above file. I have written the below code:

# Fetching the date vlaue from the filename
a<-substr(gsub("[A-z]|[////]","",file),6,13)
 a
[1] "20150115"
hrs<-substr(gsub("[A-z]|[////]","",file),14,15)
hrs
[1] "00"
#concatenating both date and a as one
chr<-paste(a,hrs, sep=" ")
chr
[1] "20150115 00"

But when I am trying to convert chr to date. I am getting NULL value.

#Converting chr variable to date
datetime<-as.Date(a,format="%Y%m%d %H")

Result:
datetime
[1] NA

Problem 2: I want to fetch 264 from the file name. Code for this is given below:

validhrs<-substr(gsub("[A-z]|[////]","",ncfname),17,19)
Result:
validhrs
[1] "264"

I want to convert this validhr to time(hour).And then add this to datetime

Anyone could help me with this?

Thanks in advance!!

Kaushik
  • 193
  • 2
  • 11

1 Answers1

1

Answer to Question 1: How to extract date from string, then convert it to date class:

x <- "/path/path/path/pth.0p25.2015011501.p264.path2.pathpathh254004.nc"

#Extract the date:
x <- gsub(".*(\\d{10}).*",'\\1',x)

#Convert to POSIXct:
x <- as.POSIXct(x,format="%Y%m%d %H")

Output:

[1] "2015-01-15 01:00:00 PST"

Answer to Question 2: How to add number of hours, "...p264..." in this case, to x:

hrs <- gsub(".*[p]+(\\d{3}).*","\\1",x)

require(lubridate)

x + hours(hrs)

Output:

[1] "2015-01-26 01:00:00 PST"

Note: 264 hours (i.e. 11 days) were added to what was once "2015-01-15 01:00:00".

www
  • 4,034
  • 1
  • 9
  • 22