How to convert date from mm/dd/YYYY to dd/mm/YYYY in R?

安稳与你 提交于 2020-05-01 09:48:51

问题


Crime analysis data in R:

Let's say I have a very large dataset with millions of columns. One of the column has Dates such as "3/28/2020" (mm/dd/YYYY) format.

For my analysis, I need a format (dd/mm/YYYY)

I have a sample code:

conv <- function(a)
{ 
  dd <- strsplit(a,"/")[[1]][2]
  mm <- strsplit(a,"/")[[1]][1]
  yyyy <- strsplit(a,"/")[[1]][3]
  com <- paste(dd,mm,yyyy,sep="/")
  return(com)
             }
   a <- as.character(crime.data$Arrest.Date)
   conv(a)

When I do this, I get converted date but only one. That is, it only outputs the date date in column. I want all the dates to convert.

Is there any way I can do that in R? or any other function in R?


回答1:


Don't use regex or string manipulation for date-time operations.

Convert to standard date class and then use format to get data in desired format.

format(as.Date('3/28/2020', '%m/%d/%Y'), '%d/%m/%Y')
#[1] "28/03/2020"



回答2:


We can use lubridate

library(lubridate)
format(mdy("3/28/2010"), "%d/%m/%Y")


来源:https://stackoverflow.com/questions/61315348/how-to-convert-date-from-mm-dd-yyyy-to-dd-mm-yyyy-in-r

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!