问题
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