josie
josie

Reputation: 3

R function to adjust column type to date format

I have a decent-sized dataset converted from csv. files that includes a date column. I need to convert this column from character type to date format. I have tried using parse_date function but it keeps returning an error:

 library(tidyverse)

 file1 <- read_csv(file1, na = "-", skip = 7)

 file1$Date <- parse_date(file1$Date, format ="%Y-%B-%d")

Warning: 31 parsing failures.

or..

Error in parse_vector(x, col_date(format), na = na, locale = locale, trim_ws = trim_ws) : 
 is.character(x) is not TRUE

How do I fix this? Any guidance would be greatly appreciated.

EDIT::

 Date       `Minimum temper~ `Maximum temper~ `Rainfall (mm)` 
 <date>                <dbl>            <dbl>           <dbl>            
       
 1 NA                      7.6             15.4             0   NA                            
 2 NA                     -3.8             14.3             0   NA                              
 3 NA                     -3.6             19.5             0   NA                            
 4 NA                      3.7             12.8            13.8 NA                             
 5 NA                     -1               15               0   NA                           
 6 NA                      1.2             13.7             0   NA                            
 # ... with 15 more variables: `Direction of maximum wind gust` <chr> etc..

Original file1

  Date  `Minimum temper~ `Maximum temper~ `Rainfall (mm)` 
   <chr>            <dbl>            <dbl>           <dbl>            
  1 1/08~              7.6             15.4             0                
  2 2/08~             -3.8             14.3             0                
  3 3/08~             -3.6             19.5             0               
  4 4/08~              3.7             12.8            13.8              
  5 5/08~             -1               15               0                 
  6 6/08~              1.2             13.7             0              
      # ... with 15 more variables: 

Upvotes: 0

Views: 218

Answers (2)

akrun
akrun

Reputation: 887591

We can use anydate from anytime

library(anytime)
file1$Date <- anydate(file1$Date)

Upvotes: 0

Ronak Shah
Ronak Shah

Reputation: 389175

You can use as.Date with correct format :

file1$Date <- as.Date(file1$Date, '%d/%m/%Y')

Or with lubridate :

file1$Date <- lubridate::dmy(file1$Date)

Upvotes: 2

Related Questions