简体   繁体   English

如何将 R 中数据框的部分日期转换为日期列?

[英]How to convert a partial date for a dataframe in R into a date column?

So assuming I have a df like:所以假设我有一个 df 像:

   <chr>          <chr>            <chr>
  Category        Date             Type
1 x               Jan 2              g
2 x2              Jan 5              a
3 x3              Mar 7              b
4 x4              Apr 9              c 
5 x5              Dec 12             o

How would I use the lubridate library to convert my character dates into actual dates?我将如何使用 lubridate 库将我的角色日期转换为实际日期?

I've been trying to use lubridate but not sure how to convert the chars into number eg Jan into 1, Mar into 3 or directly convert them given that they aren't in the mdy() function scope as they are partial dates.我一直在尝试使用 lubridate 但不确定如何将字符转换为数字,例如 Jan 转换为 1,Mar 转换为 3 或直接转换它们,因为它们不在 mdy() 函数范围内,因为它们是部分日期。

Just provide a year:只需提供一年:

x <- c("Jan 2")
as.Date(paste0("2020 ", x), "%Y %b %d")
# "2020-01-02"

We can use我们可以用

library(lubridate)
mdy(x, truncated = 2)
#[1] "2020-01-02"

data数据

x <- "Jan 2"

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

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