Convert months mmm to numeric

前端 未结 4 1806
粉色の甜心
粉色の甜心 2020-12-09 08:07

I have been given a csv with a column called month as a char variable with the first three letters of the month. E.g.:

\"Jan\", \"Feb\",\"Mar\",...\"Dec\"
         


        
4条回答
  •  隐瞒了意图╮
    2020-12-09 08:57

    You can use the built-in vector month.abb to check against when converting to a number, eg :

    mm <- c("Jan","Dec","jan","Mar","Apr")
    
    sapply(mm,function(x) grep(paste("(?i)",x,sep=""),month.abb))
    Jan Dec jan Mar Apr 
      1  12   1   3   4 
    

    The grep construct takes care of differences in capitalization. If that's not needed,

    match(mm,month.abb) 
    

    works just as fine.

    If you also have a day and a year column, you can use any of the conversion functions, using the appropriate codes (see also ?strftime)

    eg

    mm <- c("Jan","Dec","jan","Mar","Apr")
    year <- c(1998,1998,1999,1999,1999)
    day <- c(4,10,3,16,25)
    
    dates <- paste(year,mm,day,sep="-")
    
    strptime(dates,format="%Y-%b-%d")
    [1] "1998-01-04" "1998-12-10" "1999-01-03" "1999-03-16" "1999-04-25"
    

提交回复
热议问题