The year is in factor type. I want to convert as date. How do I convert it to date?data set image
Asked
Active
Viewed 83 times
0
-
1There are lots of ways to do this, but if you have data for fiscal years, why not keep it in fiscal years for plotting? – Allan Cameron Apr 13 '22 at 19:55
-
2It's easier to help you if you include a simple [reproducible example](https://stackoverflow.com/questions/5963269/how-to-make-a-great-r-reproducible-example) with sample input and desired output that can be used to test and verify possible solutions. – MrFlick Apr 13 '22 at 19:56
-
Do not post data or code as an image. Share data in a [reproducible format](https://stackoverflow.com/questions/5963269/how-to-make-a-great-r-reproducible-example). Make it clear what the expected output is. A Date value in base R cannot have more than one year. What do you want to do with the date? – MrFlick Apr 13 '22 at 20:11
1 Answers
0
Suppose you have:
my_df <- data.frame(year = as.factor(c("1983-84", "1984-85")))
You could extract the ending year using:
my_df$year_num = as.numeric(substr(as.character(my_df$year), 1, 4)) + 1
This takes the year
variable which is a factor, converts it to character based on its labels, extracts the first 4 characters (the starting year), converts to number, and adds one. If you want year_num
to instead show the starting year, skip that last step.
You could also specify a specific date like the last day of the FY (assuming here June 30th) using:
my_df$FY_end = as.Date(paste0(my_df$year_num, "-06-30"))
Result
year year_num FY_end
1 1983-84 1984 1984-06-30
2 1984-85 1985 1985-06-30
> str(my_df)
'data.frame': 2 obs. of 3 variables:
$ year : Factor w/ 2 levels "1983-84","1984-85": 1 2
$ year_num: num 1984 1985
$ FY_end : Date, format: "1984-06-30" "1985-06-30"

Jon Spring
- 55,165
- 4
- 35
- 53
-
Thank you, but I want to keep 1983-84 as the date formate. I do not know how to do that. – Rakin Zaman Apr 13 '22 at 20:12
-
"1983-84" is a character string. You could specify a date like the starting or ending date, but you seem to be describing a type of "date" that I've never encountered. – Jon Spring Apr 13 '22 at 20:14