Lubridate 中的年份函数不仅按计划计算年份

Year function in Lubridate is not only taking the year as planned

我一直在尝试使用 lubridate 中的年份函数从日期中仅提取年份,但它仍然保留了整个日期。谁能帮我解决这个问题?

        data %>% 
        select(ID, Author, Date, Location, Treatment) %>%     
        distinct() %>%
        drop_na() %>%   
        mutate(year = lubridate::year(Date)) %>% 
        unite('Study', Author, Date, Location, sep = " ", remove = T, na.rm = F) %>% 
        flextable() %>% 
        autofit()
  
           }

您的问题是 class(data$Dates) 是一个字符列。它需要 class "Date" 才能 year 了解哪部分是年份。

as.Date 在传递字符串时检查的默认格式是:c("%Y-%m-%d", "%Y/%m/%d"),它与您的字符列的格式相匹配(例如 YYYY-数字月-日)。

library(lubridate)
library(dplyr)

data %>% 
  mutate(year = year(as.Date(Dates)))

输出

       Dates year
1 1999-01-01 1999
2 1999-01-01 1999
3 1999-01-01 1999
4 1999-01-01 1999
5 1999-01-01 1999
6 1999-01-01 1999

数据

data <- structure(list(Dates = c("1999-01-01", "1999-01-01", "1999-01-01", 
"1999-01-01", "1999-01-01", "1999-01-01")), class = "data.frame", row.names = c(NA, 
-6L))