Search code examples
rdatedataframedata-extraction

Converting number variable to date (formatted DD-MMM-YY)


dataframe in R. It shows a number of names and events occurring on different dates. I need the date column to show as the format 02-Jan-16 instead of "2" (see first row).

Any advice you have would be greatly appreciated.

NAME    date    modality
Name.1   2      HA
Name.2   2      H
Name.2   4      H
Name.2   6      H
Name.2   8      H
Name.2   9      H
Name.2   11     H
Name.2   13     H
Name.2   15     H
Name.2   16     H
Name.2   18     H
Name.2   20     H
Name.2   22     H
Name.2   23     H
Name.2   25     H
Name.2   27     H
Name.2   29     H
Name.2   30     H
Name.3   2      HA
Name.3   3      HA
Name.3   4      HA
Name.4   1      H
Name.4   2      H
Name.4   3      H
Name.4   4      H
Name.4   5      H
Name.4   6      H
Name.4   7      H
Name.4   8      H
Name.4   9      H
Name.4   10     H
Name.4   11     H
Name.4   12     H
Name.4   13     H
Name.4   14     H
Name.4   15     H
Name.4   16     H
Name.4   17     H
Name.4   18     H
Name.4   19     H
Name.4   20     H
Name.4   21     H
Name.4   22     H
Name.4   23     H
Name.4   24     H
Name.4   25     H
Name.4   27     H
Name.4   28     H
Name.4   29     H
Name.4   30     H
Name.4   31     H
Name.5   17     HA
Name.5   18     HA

Just a collection of 5 names, have many more to process


Solution

  • Since there are only single numbers in date column, I assumed that they are the days of January-2016. I've created a dataframe, similar to yours:

    NAME <- c("Name1", "Name2", "Name3")
    date <- c("2","2","4")
    modality <- c("HA","H","H")
    df <- data.frame(NAME, date, modality)
    

    From this point, simply paste can do the trick

    df$date <- paste(df$date,"Jan-16", sep="-")
    df
    

    which returns just as you wish,

       NAME     date modality
    1 Name1 2-Jan-16       HA
    2 Name2 2-Jan-16        H
    3 Name3 4-Jan-16        H
    

    Further, you can use as.Date function on date column to convert them into dates with proper format.