如何在 R 中将 05/02/1953 更改为仅 1953(即 dd/mm/yyyy 到 yyyy)?



我正在尝试比较两个基于时间的数据集。一个只是以"yyyy"格式写的年份,但另一个有"dd/mm/yyyy"。有没有办法将所有这些转换为简单的年份格式?

下面是一个lubridate的例子:

library(lubridate)
#> 
#> Attaching package: 'lubridate'
#> The following object is masked from 'package:base':
#> 
#>     date
x <- "05/02/1953"
full_date <- lubridate::mdy(x)
class(full_date)
#> [1] "Date"
just_the_year <- year(full_date)
just_the_year
#> [1] 1953

下面是如何更改整个数据框中的日期的示例:

library(tidyverse)
new_df <- df %>%
mutate(full_date = lubridate::mdy(x)) %>%
mutate(just_the_year = year(full_date))

这将在数据框中创建两个新列,其中日期为日期而不是字符串,并且仅创建年份。

我们可以使用base R中的format

as.integer(format(as.Date("05/02/1953", "%d/%m/%Y"), "%Y"))
#[1] 1953

或与strptime

strptime("05/2/1953", "%d/%m/%Y")$year + 1900
#[1] 1953

最新更新