我有一个称为日期的数据框,如下所示:
Day Month Year
2 April 2015
5 May 2014
23 December 2017
此代码是:
date <- data.frame(Day = c(2,5,23),
Month = c("April", "May", "December"),
Year = c(2015, 2014, 2017))
我想创建一个新的列,如下所示:
Day Month Year Date
2 April 2015 2/4/2015
5 May 2014 5/5/2014
23 December 2017 23/12/2017
为此,我尝试:
data <- data %>%
mutate(Date = as.Date(paste(Day, Month, Year, sep = "/"))) %>%
dmy()
但是我收到一条错误消息:
Error in charToDate(x) :
character string is not in a standard unambiguous format
我没有看到明显的错误吗?
非常感谢您。
答案 0 :(得分:2)
我们需要在as.Date
中使用适当的格式。使用基数R,我们可以做到
transform(data, Date = as.Date(paste(Day, Month, Year, sep = "/"), "%d/%B/%Y"))
# Day Month Year Date
#1 2 April 2015 2015-04-02
#2 5 May 2014 2014-05-05
#3 23 December 2017 2017-12-23
或者使用dplyr
和lubridate
library(dplyr)
library(lubridate)
data %>% mutate(Date = dmy(paste(Day, Month, Year, sep = "/")))
如果需要更改显示格式,可以添加format(Date, "%d/%m/%Y")
。