Reputation: 15
I have a csv file which i loaded into R. One of the column called "remaining_lease" contains data of year and month, such as "56 years 04 months". i would like to convert it into year and save it into a new column. how do I do that? thank you
Upvotes: 0
Views: 58
Reputation: 66490
library(tidyverse); library(lubridate)
# fake data
data.frame(remaining_lease = c("56 years 04 months", "20 years")) %>%
# split into columns, convert to numbers, add as months, extract year
separate(remaining_lease, c("years", "months"), sep = "years") %>%
mutate(across(years:months, ~coalesce(parse_number(.), 0)),
date = Sys.Date() %m+% months(months + 12*years),
year = year(date))
Result
years months date year
1 56 4 2079-05-10 2079
2 20 0 2043-01-10 2043
Upvotes: 1