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. I'm not having trouble parsing the date format, but in applying lubridate over multiple columns. 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
.
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'
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]
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.