使用lubridate和dplyr将多列转换为日期 [英] Convert multiple columns to dates with lubridate and dplyr

查看:70
本文介绍了使用lubridate和dplyr将多列转换为日期的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在寻找一种简单的方法来使用lubridate::dmy()将以'date'开头的数据帧中的所有变量转换为使用lubridate::dmy()的日期(它们当前是dmy格式的字符).

I'm looking for a straightforward way to convert all of the variables in a data frame which begin with 'date' to dates using lubridate::dmy() (they are currently characters with the dmy format).

我曾以为dplyr中的mutate_if或mutate_each会完成,但我一直在努力寻找方法.

I had thought there would be done with mutate_if or mutate_each in dplyr but I am struggling to figure out how.

推荐答案

您可以使用mutate_at()

library(dplyr)
library(lubridate)

df <- mutate_at(df, vars(starts_with("date")), funs(dmy))

或使用mutate_if将所有日期列突变为dmy.使用lubridate中的is.Date.

or use mutate_if to mutate all date columns to dmy. Using is.Date from lubridate.

df  <- mutate_if(df, is.Date, funs(dmy))

这篇关于使用lubridate和dplyr将多列转换为日期的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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