You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何在R语言中将字符串转换为日期?含特定格式转换问询

Great questions! Let's break this down step by step to solve your R date conversion needs.

1. How to Convert Strings to Dates in R?

Converting strings to date objects in R is a common task, and you have two reliable approaches: using base R functions, or leveraging the flexible lubridate package (my go-to for date handling).

Base R: as.Date()

The core as.Date() function works when you specify the format of your string using these common format codes:

  • %Y: 4-digit year (e.g., 2020)
  • %m: 2-digit month (01-12)
  • %d: 2-digit day (01-31)
  • %b: Abbreviated month name (Jan, Feb)
  • %B: Full month name (January, February)

Examples of how to use it:

# Standard "YYYY-MM-DD" format (no need to specify format)
date_str1 <- "2020-01-19"
as.Date(date_str1)

# "DD/MM/YYYY" format (requires explicit format)
date_str2 <- "19/01/2020"
as.Date(date_str2, format = "%d/%m/%Y")

# String with full month name
date_str3 <- "January 19, 2020"
as.Date(date_str3, format = "%B %d, %Y")

lubridate Package (Simpler & More Flexible)

lubridate takes the guesswork out of date formats—you just need to match the order of day/month/year in your string with the corresponding function:
First install and load the package:

install.packages("lubridate")
library(lubridate)

Then use these intuitive functions:

# For "YYYY-MM-DD"
ymd("2020-01-19")

# For "DD/MM/YYYY"
dmy("19/01/2020")

# For "Month Day, Year"
mdy("January 19, 2020")

2. Converting "19th January 2020" to a Standard R Date Object

The catch here is the ordinal suffix (th) attached to the day. Base R's as.Date() can't parse this directly, but we have two easy workarounds:

Method 1: Clean the String First

Use regex to strip off ordinal suffixes (st, nd, rd, th) before converting. You can use base R or the stringr package for this:

# Load stringr (install first if needed: install.packages("stringr"))
library(stringr)

date_str <- "19th January 2020"
# Remove ordinal suffixes with regex
clean_date <- str_replace(date_str, "(\\d+)(st|nd|rd|th)", "\\1")
# Now convert the cleaned string
as.Date(clean_date, format = "%d %B %Y")

Method 2: Let lubridate Handle It

lubridate's functions are smart enough to ignore ordinal suffixes automatically:

library(lubridate)
date_str <- "19th January 2020"
# dmy() matches day-month-year order and skips the "th"
dmy(date_str)

This will directly return a standard R Date object: [1] "2020-01-19"


内容的提问来源于stack exchange,提问作者Bogaso

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.07 09:23:12