[英]How do you convert multiple columns to date format in R using lubridate?
I have a database with multiple columns of dates as character class. 我有一个数据库,其中包含多列日期作为字符类。 I want to use the lubridate package in R to convert them all at once.
我想在R中使用lubridate包来一次转换它们。 I'm not having trouble parsing the date format, but in applying lubridate over multiple columns.
我没有解析日期格式,但在多列上应用lubridate。 Any suggestions?
有什么建议么?
crimes.df <- data.frame(offense.date = c('06102003', '05122006'), charge.date = c('07152003', '10012010'))
I have tried 我努力了
crimes.df[,1:2]<-mdy(crimes.df[,1:2])
and 和
crimes.df[,1:2]<-lapply(crimes.df[,1:2], function(x) mdy(crimes.df[,1:2]))
both return this error: 都返回此错误:
Warning message:
All formats failed to parse. No formats found.
(and, inconveniently, wipe out all data in the columns.) (并且,不方便地,清除列中的所有数据。)
Using lapply
, we are looping the columns of the dataset and the function mdy
is applied on each column
. 使用
lapply
,我们循环数据集的列,并在每column
上应用函数mdy
。
crimes.df[] <- lapply(crimes.df, mdy)
In the OP's code, if we are calling the anonymous function ( function(x)
), then the function ( mdy
) should be applied on 'x' 在OP的代码中,如果我们调用匿名函数(
function(x)
),那么函数( mdy
)应该应用于'x'
crimes.df[] <- lapply(crimes.df, function(x) mdy(x))
Also, note that since there are only 2 columns, we don't need to specify the crimes.df[,1:2]
另请注意,由于只有2列,我们不需要指定
crimes.df[,1:2]
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.