How you change date format to only year? what functions shoud I use
Hi @saad_el_eulj,
Welcome to the RStudio Community Forum.
Here is a simple way to extract the year from a date, and deliver the result as a number, using the year()
function from the {lubridate} package:
library(lubridate)
#>
#> Attaching package: 'lubridate'
#> The following objects are masked from 'package:base':
#>
#> date, intersect, setdiff, union
year(as.Date("2015-05-17"))
#> [1] 2015
Created on 2021-05-25 by the reprex package (v2.0.0)
how can you convert if you already have a column date example row : 2015-01-01 to only 2015
You can use str_sub()
from the stringr
package
suppressMessages(library(tidyverse))
x <- Sys.Date()
x
#> [1] "2021-05-25"
the_year <- stringr::str_sub(string = x, start = 1, end = 4)
the_year
#> [1] "2021"
class(the_year)
#> [1] "character"
# Optionally - if you want year to be numeric
#as.numeric(the_year)
Hi @Dobrokhotov1989
let's say i alrady have a date column that I want to convert it to only year.
Example of the row format: 2015-01-01 I want only to keep the 2015 and drop month and days.
How is it different from the example I've provided?
In case of a data.frame
you just apply str_sub()
function to you date column
suppressMessages(library(tidyverse))
df %>%
mutate(year = stringr::str_sub(string = date, start = 1, end = 4))
This topic was automatically closed 21 days after the last reply. New replies are no longer allowed.
If you have a query related to it or one of the replies, start a new topic and refer back with a link.