The year is in factor type. I want to convert as date. How do I convert it to date?data set image
CodePudding user response:
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"