Sometimes your survey data may contain information about the date the respondents completed the survey stored as categories rather than as date values. Suppose you have a variable in your data file called Week that encodes the week of the survey in Categorical format. This article shows you how to create a new JavaScript variable which has date values derived from categories, going from this:
To a variable where you can change the Structure to Date/Time to use it as a date variable set.
Requirements
- A data set loaded into Displayr that contains a categorical variable that requires converting to a Date/Time variable, e.g. year, quarter, month, or week.
Method
- Hover over any variable in your Data Sets tree > Plus (+) > Insert Variable(s) > Custom Code > JavaScript - Numeric.
- For the example above, copy and paste this code into the JAVASCRIPT CODE in the object inspector under Properties
if (week == 1) Q.EncodeDate(2021,01,04);
else if (week == 2) Q.EncodeDate(2021,01,11);
else if (week == 3) Q.EncodeDate(2021,01,18);
else if (week == 4) Q.EncodeDate(2021,01,25);
else if (week == 5) Q.EncodeDate(2021,02,01);
else if (week == 6) Q.EncodeDate(2021,02,08);
else if (week == 7) Q.EncodeDate(2021,02,15);
else if (week == 8) Q.EncodeDate(2021,02,22);
else if (week == 9) Q.EncodeDate(2021,03,01);
else if (week == 10) Q.EncodeDate(2021,03,08);
else if (week == 11) Q.EncodeDate(2021,03,15);
else if (week == 12) Q.EncodeDate(2021,03,22);
else if (week == 13) Q.EncodeDate(2021,03,29);
else if (week == 14) Q.EncodeDate(2021,04,05);
else if (week == 15) Q.EncodeDate(2021,04,12);
else if (week == 16) Q.EncodeDate(2021,04,19);
else if (week == 17) Q.EncodeDate(2021,04,26);
else if (week == 18) Q.EncodeDate(2021,05,03);
else if (week == 19) Q.EncodeDate(2021,05,10);
else NaN; - Give the variable a Label and Name under Properties > GENERAL.
- Finally, change the variable Structure to Date/Time to use it as a date variable set.
- Click Calculate.
In the JavaScript code above, I've used the input variable week, which is the categorical variable present in my data set that I needed to convert. You will need to replace "week" in the code above with the name of the variable that contains your categorical date variable. You will also notice that I've set my week start dates within parentheses in the Q.EncodeDate() function. You will need to update this specific the dates that are appropriate for your data. If you are using a categorical variable that represents "month" for example, you would use:
if (month == 1) Q.EncodeDate(2021,01,01);
else if (month == 2) Q.EncodeDate(2021,02,01);
and so on and so forth.
You can further adjust the date aggregation on your new Date/Time variable by clicking on DATA VALUES > Date/Time from the object inspector and set the aggregation level to your liking.
Next
How to Work with Aggregated Dates Using R