英文:
Extracting year from date time variable
问题
I would only like to extract '2021' from this.
By the way, the class
for this variable is 'character'.
英文:
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"
答案1
得分: 2
以下是一个基本的R解决方案:
as.numeric(format(as.POSIXct("2/10/21 6:55", format = "%m/%d/%y %H:%M"), "%Y"))
[1] 2021
<details>
<summary>英文:</summary>
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
</details>
# 答案2
**得分**: 1
library(lubridate)
"2/10/21 6:55" |> mdy_hm() |> year()
[1] 2021
<details>
<summary>英文:</summary>
library(lubridate)
"2/10/21 6:55" |> mdy_hm() |> year()
[1] 2021
</details>
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论