5

I would like R to recognize one column as date. It is read as factor during the import, however, when I try to format with 'as.Date' and 'format' I only get NAs. I'm not sure where I'm going wrong.

> d = read.table("ByMonth.Year_54428.txt", header=T, sep=",")  
> str(d)  
'data.frame':   607 obs. of  2 variables:
 $ V1  : Factor w/ 607 levels "1950-12","1951-01",..: 1 2 3 4 5 6 7 8 9 10 ...
 $ Rain: int  100 56000 29293 37740 19649 41436 58067 51082 49629 62680 ...
> 
> 
> Date.form1 <- as.Date(d$V1, "%Y-%m")
> str(Date.form1)
 Date[1:607], format: NA NA NA NA NA NA NA NA NA NA NA NA NA NA ...
> 
> Date.form2 = as.Date(as.character(d$V1), format="%Y-%m")
> str(Date.form2)
 Date[1:607], format: NA NA NA NA NA NA NA NA NA NA NA NA NA NA ...
David Arenburg
  • 91,361
  • 17
  • 137
  • 196
KG12
  • 77
  • 1
  • 1
  • 8

1 Answers1

15

A year and a month do not make a date. You need a day also.

d <- data.frame(V1=c("1950-12","1951-01"))
as.Date(paste(d$V1,1,sep="-"),"%Y-%m-%d")
# [1] "1950-12-01" "1951-01-01"

You could also use the yearmon class in the zoo package.

library(zoo)
as.yearmon(d$V1)
# [1] "Dec 1950" "Jan 1951"
Joshua Ulrich
  • 173,410
  • 32
  • 338
  • 418
  • ah, thanks! I didn't know that as.Date needs a day as well because I got the data by using: `ByMonth.Year = rowsum(out$rain_fall, format(out$Date,"%Y-%m"))` which doesn't use a day. Thanks again! – KG12 May 07 '13 at 09:46
  • Of course `as.Date` needs a day. If I asked you, "what day were you born?", you wouldn't answer, "December 1950". As it says in the _Value_ section of `?format`, `format` converts its object to a character vector. – Joshua Ulrich May 07 '13 at 13:17