0

Okay, so here's a sample of what I have in a data frame

months   other_column1   other_column2    ...
01-1912  ...             ...
02-1912  ...             ...
03-1912  ...             ...
...

Now, I'm trying to convert the column "months" to be the index of the time series, so this is what I'm doing at the moment to try and make it a Date object:

dates <- as.Date(df$months, format="%m-%Y")

This goes through with no error messages, but all I get is a vector full of NA instead of the dates. Any ideas? Do you need more information, don't know what to tell more really?

New to R, seems to be quite powerful, so I'm trying to learn some. Thanks.

Roope
  • 4,469
  • 2
  • 27
  • 51
  • 1
    You can replace your entire first paragraph with a simple sample of your actual data. – Roman Luštrik Mar 13 '14 at 20:51
  • 2
    A year and month does not define a date. See http://stackoverflow.com/questions/6242955/converting-year-and-month-to-a-date-in-r – mnel Mar 13 '14 at 21:00
  • You need to add a day, look at this for more details http://stackoverflow.com/questions/22387617/sort-a-matrix-with-dates-by-columns-and-rows-in-r – infominer Mar 13 '14 at 21:02
  • of course a date needs a day ... that is not specific to R :) – Raffael Mar 13 '14 at 21:03
  • `z <-"01-2014" # M/Y format like you have.` `as.Date(z) # this gives NA` `z <-"01-01-2014"` `as.Date(z) #this gives an interesting answer, have fun figuring this out` `as.Date(z,"%m-%d-%Y") #"2014-01-01" this will give what you want with day added.` – infominer Mar 13 '14 at 21:04
  • 1
    If year and month are all you need, you could use the `yearmon` class from the `zoo` package. – Brian Diggs Mar 13 '14 at 21:06
  • Okay I think xts will have to go, zoo it is. Thanks – Roope Mar 13 '14 at 21:12
  • But I guess mnel solved the actual question here so if you want to make it an answer I'll give you the points, thanks. – Roope Mar 13 '14 at 21:13

1 Answers1

0

As you said you need last of the month Try this, courtesy https://stackoverflow.com/a/8334531/2747709 from @DirkEddelBuettel

seq(as.Date("YYYY-MM-DD"), length="No. of Months", by="1 month") - 1

let's start from the beginning, creating your data

data.foo <- data.frame(months=c("01-1912","02-1912","03-1912"),col1=rnorm(3),col2=rnorm(3))
#creating dates, note the format
data.foo$dates <-as.Date(paste("01",data.foo$months,sep="-"),"%d-%m-%Y") 
#getting the last date using code above
data.foo$lastday <- seq(as.Date(data.foo$dates)[2],length=nrow(data.foo), by ="1 month") -1
Community
  • 1
  • 1
infominer
  • 1,981
  • 13
  • 17