Home » excel » r – Assign index values on dates in Excel

r – Assign index values on dates in Excel

Posted by: admin May 14, 2020 Leave a comment

Questions:

I have a seemingly easy to solve question, but I am really stuck! I have a set of dates and I am aiming to assign an index value to those dates. Specifically, I want each month of each year to have a unique index value. For visualization of what I want to do, I have the following dates where as you can see January 96 has the value of 1, February 96 is 2, March 96 is 3 and so on. Note: there are many years as well from 1996 to 2018, which means that Jan 1997 should have the value 13 in the index.

Date         Index
01/01/1996    1
02/01/1996    1
03/01/1996    1
04/01/1996    1
05/01/1996    1
08/01/1996    1
01/02/1996    2
02/02/1996    2
05/02/1996    2
06/02/1996    2
07/02/1996    2
08/02/1996    2
09/02/1996    2 
01/03/1996    3
04/03/1996    3
05/03/1996    3
06/03/1996    3
07/03/1996    3
08/03/1996    3
11/03/1996    3

I am trying to achieve this either in R, or Excel.

How to&Answers:

Assuming that you read in your dates in R and they are of type character and not Date, this would work:

mydf$index2 <- as.numeric(as.factor(substring(mydf$Date, 4)))
mydf
#         Date Index Index2
#1  01/01/1996     1      1
#2  02/01/1996     1      1
#3  03/01/1996     1      1
#4  04/01/1996     1      1
#5  05/01/1996     1      1
#6  08/01/1996     1      1
#7  01/02/1996     2      2
#8  02/02/1996     2      2
#9  05/02/1996     2      2
#10 06/02/1996     2      2
#11 07/02/1996     2      2
#12 08/02/1996     2      2
#13 09/02/1996     2      2
#14 01/03/1996     3      3
#15 04/03/1996     3      3
#16 05/03/1996     3      3
#17 06/03/1996     3      3
#18 07/03/1996     3      3
#19 08/03/1996     3      3
#20 11/03/1996     3      3

mydf is your data.frame name. In the code above, I subset the date to extract the month and the year, then convert into factor and then into numeric which creates the indices.