1

I have nc file where time unit is expressed as year and month in format "month as %Y%m.%f", type: character. For example, 199604.5 represents the year 1996, month 04. How to convert time in date format?

I tried next:

as.Date(ncin$dim$time$vals, "%Y%m.%f")

But I got the next error:

Error in charToDate(x) : 
  character string is not in a standard unambiguous format

I also tried next:

as.Date(ncin$dim$time$vals)

but I got the wrong dates.

"2516-07-01" "2516-07-02" "2516-07-03" "2516-07-04" "2516-07-05" "2516-07-06"
  • What is the number after the dot (5 in your example)? – Dataform May 14 at 18:27
  • I don't know. Data are monthly. standard_name: time units: month as %Y%m.%f calendar: proleptic_gregorian axis: T – Славица Малиновић-Милићевић May 14 at 20:38
  • What do you get if you print(ncin$dim$time$vals) ? – Dataform May 15 at 6:02
  • [1] 199604.5 199605.5 199606.5 199607.5 199608.5 199609.5 199610.5 199611.5 199612.5 199701.5 199702.5 199703.5 [13] 199704.5 199705.5 199706.5 199707.5 199708.5 199709.5 199710.5 199711.5 199712.5 199801.5 199802.5 199803.5 – Славица Малиновић-Милићевић May 15 at 8:00
  • And class(ncin$dim$time$vals) ? – Dataform May 15 at 8:07
0

I'm not a regular R user so I can't give the complete answer. Based on the comments to the question it seems that ncin$dim$time$vals is a numeric array containing values like

[1] 199604.5 199605.5 199606.5 199607.5 199608.5 199609.5 199610.5 199611.5 199612.5 
199701.5 199702.5 199703.5 [13] 199704.5 199705.5 199706.5 199707.5 199708.5 199709.5 
199710.5 199711.5 199712.5 199801.5 199802.5 199803.5

A single element in the array can be parsed to a date with this function

ymdouble2date <- function (d) {
  d <- floor(d)
  y <- floor(d / 100)
  m <- d - 100*y
  as.Date(ISOdate(y, m, 1))
}

So ymdouble2date(199604.5) gives a date 1996-04-01. The above function ignores the fraction part but can be changed to give another day than the first day of the month.

The problem is that I don't think you can have an array of dates. So this

dates <- lapply(ncin$dim$time$vals, ymdouble2date)

gives a list of the dates. And if you try to get an array

d <- dim(ncin$dim$time$vals)
dates <- sapply(ncin$dim$time$vals, ymdouble2date)
dim(dates) <- d

then you get an array of numbers representing the dates as the number of days since 1970-01-01.

| improve this answer | |

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.