问题
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
.
Here is some sample data using just two columns
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)
I've tried:
df <- df %>% mutate(df, funs(ymd))
and
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)
}
That didn't work either.
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.
回答1:
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
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
).
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
回答2:
EDIT: This time with the right wildcards for the as.Date
function. I also added a reproducible example:
library(dplyr)
df <- data.frame(date_1 = c("2019-01-01", "2019-01-02", "2019-01-03"),
date_2 = c("2019-01-04", "2019-01-05", "2019-01-06"),
value = c(1,2,3),
stringsAsFactors = F)
str(df)
date_cols <- c("date_1", "date_2")
df_2 <- df %>%
mutate_at(vars(date_cols), funs(as.Date(., "%Y-%m-%d")))
str(df_2)
来源:https://stackoverflow.com/questions/48501059/change-multiple-character-columns-to-date