0

I have some date/times in a variable where I would only like to extract the year.

Here is an example:

2/14/21 4:55

I would only like to extract '2021' from this.

By the way, the class for this variable is 'character'.

> class(df$DTS)
[1] "character"
Jamie
  • 543
  • 7
  • You can't "extract" `2021` from your sample data, since it's not actually there. Does every element of your data follow the format you've given? If so, simple substrings followed by concatenation would work. otherwise, a more robust sultion would involve conversion to a `DateTime` followed by extraction of the year. By the way, your example is ambiguous: does it use the format `d/m/y` or `m/d/y`? It's impossible to tell... – Limey May 22 '23 at 17:08

2 Answers2

2

Here is a base R solution:

as.numeric(format(as.POSIXct("2/10/21 6:55", format = "%m/%d/%y %H:%M"), "%Y"))

[1] 2021
TarJae
  • 72,363
  • 6
  • 19
  • 66
1
library(lubridate)
"2/10/21 6:55" |> mdy_hm() |> year()
# [1] 2021
Gregor Thomas
  • 136,190
  • 20
  • 167
  • 294