将多个字符列更改为日期 [英] Change multiple character columns to date

查看:82
本文介绍了将多个字符列更改为日期的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有多个字符列(大约20个),我想将所有字符列都更改为日期格式,并使用r来减少时间.我已经尝试过loopsmutateapply.

I have multiple character columns (around 20) that I would like to change all to date formats and drop the time using r. I've tried loops, mutate and apply.

有些示例数据仅用两列

col1 = c("2017-04-01 23:00:00", "2017-03-03 00:00:01", "2017-04-02 
00:00:01")
col2 = c("2017-04-10 08:41:49", "2017-04-10 08:39:48", "2017-04-10 
08:41:51")
df <- cbind(col1, col2)

我尝试过:

df <- df %>% mutate(df, funs(ymd))

df <- df %>% mutate(df, funs(mdy))

两个都给我一个错误.我还尝试过将所有列名放在列表中并进行

Both gave me an error. I've also tried putting all column names in a list and do a

for(i in namedlist) {
as_date(df[i])
glimpse(df)
}

那也不起作用.

我尝试使用的答案到使用lubridate和dplyr 的日期列,这也不起作用.该职位希望某些变量进行转换.我希望所有变量都可以转换,因此var命令不适用.

I've tried to use the answer from Convert multiple columns to dates with lubridate and dplyr and that did not work either. That posts wanted certain variables to be converted. I want all of my variables to be converted so the var command doesn't apply.

有什么建议可以有效地做到这一点?谢谢.

Any suggestions to do this efficiently? Thank you.

推荐答案

如果要对所有列进行应用,则可以使用lapply进行很短的调用.我将使用data.table传递给这里:

If you're applying over all columns, you can do a very short call with lapply. I'll pass it here using data.table:

library( data.table )
setDT( df )

df <- df[ , lapply( .SD, as.Date ) ]

在您的测试数据上,这给出了:

On your test data, this gives:

> df
         col1       col2
1: 2017-04-01 2017-04-10
2: 2017-03-03 2017-04-10
3: 2017-04-02 2017-04-10

注意:您的测试数据实际上会生成matrix,因此您需要先将其转换为data.frame(或直接转换为data.table).

NOTE: your test data actually results in a matrix, so you need to convert it to a data.frame first (or directly to a data.table).

您可以仅使用基础R来完成相同的操作,但我个人更喜欢上述解决方案:

You can do the same thing with just base R, but I personally like the above solution better:

df <- as.data.frame( lapply( df, as.Date ) )

> df
        col1       col2
1 2017-04-01 2017-04-10
2 2017-03-03 2017-04-10
3 2017-04-02 2017-04-10

这篇关于将多个字符列更改为日期的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆