jarry jafery
jarry jafery

Reputation: 1036

Date formating using zoo in R

I am working with a time series dataset in which i have months in mmm (e.g jan) format i want to convert them into mm (e.g 01). my data looks like

X            y
jan 1986    45
feb 1986    60



 data %>%
  tbl_df() %>%
  select(-X1) %>%
  separate(X,c("months","years")) %>%
  mutate(months=replace(months,months=="fab","feb")) %>%
  mutate(months =format(months,"%m",justify = "left",trim=TRUE))

when i run the above command i get the error.

`Error in eval(substitute(expr), envir, enclos) : 
  invalid 'digits' argument
In addition: Warning message:
In format.default(c("jan", "feb", "mar", "apr", "may", "jun", "july",  :
  NAs introduced by coercion`

I am using dplyr and zoo package for this.

Upvotes: 0

Views: 1162

Answers (2)

jarry jafery
jarry jafery

Reputation: 1036

Yes another way to solve this problem in an optimized way is

l<-"01"
d<-data %>%
tbl_df() %>%
select(-X1) %>%
separate(X,c("month","year")) %>%
mutate(month=replace(month,month=="fab","feb")) %>%
unite(date,year,month,sep="-") %>%
mutate(date=paste(date,l,sep="-")) %>%
mutate(date=ymd(date))

I had used lubridate package here.

Upvotes: 1

joel.wilson
joel.wilson

Reputation: 8413

is this what you are looking for?

library(zoo)
as.Date(as.yearmon(df$x), format = "%b %Y")
# [1] "1986-01-01" "2001-02-01"

# OR

month(as.yearmon(df$x)) # from data.table package
# [1] 1 2

this approach might need to have clean data. THere could definitely be better ways.

months_list <- c("jan" = 01, "feb" = 02, "mar" = 03, "apr" = 04, "may" = 05,
                 "jun" = 06, "jul" = 07, "aug" = 08, "sep" = 09, "oct" = 10,
                 "nov" = 11, "dec" = 12)

 df %>%
 select(x) %>%
 separate(x,c("months","years")) %>%
 mutate(months=replace(months,months=="fab","feb")) %>%
 mutate(months = months_list[months])
 #  months years
 #1      2  1986
 #2     12  2001

Upvotes: 2

Related Questions