[英]R array as.Date conversion
I get an array of dates from a database that I would convert to Date types. 我从数据库中获取了一个日期数组,然后将其转换为Date类型。
> dates
start finish
1 29-Oct-2017 00:00 30-Oct-2017 00:00
2 30-Oct-2017 00:00 31-Oct-2017 00:00
3 31-Oct-2017 00:00 01-Nov-2017 00:00
4 01-Nov-2017 00:00 02-Nov-2017 00:00
5 02-Nov-2017 00:00 03-Nov-2017 00:00
6 03-Nov-2017 00:00 04-Nov-2017 00:00
I can convert each column dates['start'] and dates['finish'] separately with 我可以分别转换每个列的date ['start']和dates ['finish']
> as.Date(dates['start'][,1], format="%d-%b-%Y %H:%M")
[1] "2017-10-29" "2017-10-30" "2017-10-31" "2017-11-01" "2017-11-02"
[6] "2017-11-03"
But is there a way to do it in one step? 但是,有一种方法可以一步一步做到吗?
I tried both rows simultaneously, bu that doesn't work. 我同时尝试了两行,但不起作用。
> as.Date(dates[c('start', 'finish')], format="%d-%b-%Y %H:%M")
Error in as.Date.default(dates[c("start", "finish")], format = "%d-%b-%Y %H:%M") :
do not know how to convert 'dates[c("start", "finish")]' to class “Date”
According to ?as.Date
根据
?as.Date
The as.Date methods accept character strings, factors, logical NA and objects of classes "POSIXlt" and "POSIXct".
as.Date方法接受字符串,因子,逻辑NA和“ POSIXlt”和“ POSIXct”类的对象。
Assuming that the dataset is data.frame
, it would not work as the requirements are not met. 假设数据集为
data.frame
,则由于无法满足要求,因此它将无法正常工作。 We can use lapply
to loop over the columns, apply the as.Date
to convert to Date
class and assign the output back to the columns of interest 我们可以使用
lapply
遍历列,应用as.Date
转换为Date
类,然后将输出分配回感兴趣的列
dates[c('start', 'finish')] <- lapply(dates[c('start', 'finish')],
as.Date, format = "%d-%b-%Y %H:%M")
With tidyverse
, we can use mutate_at
使用
tidyverse
,我们可以使用mutate_at
library(dplyr)
library(lubridate)
dates %>%
mutate_at(vars(start, finish), dmy_hm)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.