Home > Mobile >  How i can convert chr column into date in R?
How i can convert chr column into date in R?

Time:07-25

I have a data frame in R (xlsx file imported) that the first column contain dates with character type:

> dat
# A tibble: 4,372 x 3
   date    `1`   `2`
   <chr> <dbl> <dbl>
 1 40544  35.5  35.5
 2 40545  35.6  35.8
 3 40546  37.2  36.4
 4 40547  36.7  35.4
 5 40548  36.6  35.3

I want to convert the character type into date type in R. I tried the below code but NA's occur:

> dat%>%
    mutate(date2 = as.Date(date, format= "%m-%d-%Y"))
# A tibble: 4,372 x 4
   date    `1`   `2` date2 
   <chr> <dbl> <dbl> <date>
 1 40544  35.5  35.5 NA    
 2 40545  35.6  35.8 NA    
 3 40546  37.2  36.4 NA    
 4 40547  36.7  35.4 NA    
 5 40548  36.6  35.3 NA    

How can i fix this ? Any help ?

CodePudding user response:

Is this what you're looking for?

dat %>%
  mutate(date2 = as.numeric(date),
         date2 = as.Date(date2, origin = "1900-01-01"))
   date      date2
1 40544 2011-01-03
2 40545 2011-01-04
3 40546 2011-01-05
4 40547 2011-01-06
  • Related