简体   繁体   English

从日期列润滑提取年份

[英]lubridate extract year from date column

Based on the data and code below, when I try to extract year from the date column, I get the following error:根据下面的数据和代码,当我尝试从date列中提取year时,出现以下错误:

Error in as.POSIXlt.character(x, tz = tz(x)) : 
  character string is not in a standard unambiguous format 

Purpose: Create year and month columns from the date column目的:从日期列创建年月列

Data + code:数据+代码:

library(lubridate)

# Create sample dates
date = c("1/6/2022", "1/6/2022", "1/19/2022", "1/20/2022")

# Create a proper date column with the desired format
date_final = format(lubridate::mdy(date), '%m-%d-%Y')

# Create a year column from `date_final`
Year = lubridate::year(date_final)

base R option using format with as.POSIXct :使用as.POSIXct format的基本R选项:

date = c("1/6/2022", "1/6/2022", "1/19/2022", "1/20/2022")
dates <- as.POSIXct(date, format = '%m/%d/%Y')
format(dates, format = '%Y')
#> [1] "2022" "2022" "2022" "2022"

Created on 2022-09-29 with reprex v2.0.2创建于 2022-09-29,使用reprex v2.0.2

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM