Unable to change the format from Factor to Date in R

I have a data sample as below. Tried importing data from CSV to rstudio. Date column is recognized as factors. How to convert the format from factor to dates. I tried the below steps but no use.

  1. Tried below but getting NA NA NA as results
    library(lubridate)
    day<-as.Date(days,format='%d-%b-%y')
    day

  2. Tried below code but date and month got recognized but year is recognized as 2020 instead of 2019
    diskinfo$days <- as.Date(diskinfo$days, format = "%d/%m/%Y")
    diskinfo$days

Days Object Name Allocated GB Total MB Used MB Free MB Free Space Percent
10/03/2019 Logical Disk 60.06 52183.04 52181.42636 1.613636364 0.003092069
11/03/2019 Logical Disk 60.06 46336 46334.19101 1.808988764 0.003904292
12/03/2019 Logical Disk 60.06 61337.6 60292.54444 1045.055556 1.703820818
13/03/2019 Logical Disk 60.06 61798.4 61206.9 591.5 0.957125497
14/03/2019 Logical Disk 60.06 61071.36 58848.82341 2222.536585 3.63900927
15/03/2019 Logical Disk 60.06 61296.64 59537.09455 1759.545455 2.870468316
16/03/2019 Logical Disk 60.06 61276.16 59735.76 1540.4 2.51384392
17/03/2019 Logical Disk 60.06 61337.6 60200.93333 1136.666667 1.852990076
18/03/2019 Logical Disk 60.06 63191.04 62463.67265 727.3673469 1.151073975
19/03/2019 Logical Disk 60.06 61306.88 60851.68952 455.1904762 0.742451815
20/03/2019 Logical Disk 60.06 61450.24 60327.88583 1122.354167 1.826333629
21/03/2019 Logical Disk 60.06 56401.92 55281.68364 1120.236364 1.986173082
22/03/2019 Logical Disk 60.06 61440 60635.09524 804.9047619 1.310141265
23/03/2019 Logical Disk 60.06 60364.8 59866.43158 498.3684211 0.82566285
24/03/2019 Logical Disk 60.06 57354.24 57162.02723 192.212766 0.33511742
25/03/2019 Logical Disk 60.06 61020.16 60847.94947 172.2105263 0.282239284
26/03/2019 Logical Disk 60.06 60057.6 59960.99474 96.60526316 0.160847043
27/03/2019 Logical Disk 60.06 62853.12 62802.22811 50.89189189 0.080974741
28/03/2019 Logical Disk 60.06 60753.92 59518.47556 1235.444444 2.033545481
29/03/2019 Logical Disk 60.06 61491.2 60693 798.2 1.298047167
30/03/2019 Logical Disk 60.06 63047.68 62684.82 362.86 0.575553148
31/03/2019 Logical Disk 60.06 60231.68 59982.96 248.72 0.412916827
01/04/2019 Logical Disk 60.06 56115.2 56070.52609 44.67391304 0.079609476

Have you tried using read_csv() from readr or dmy() from lubridate? That usually does a great job of detecting the right data types. You can also set the parameter stringsAsFactors = FALSE if you are using read.csv().

I would approach it this way:

library(readr)
library(lubridate)
library(dplyr)

dat <- read_csv("file.csv") # read_csv does not have stringsAsFactors = TRUE :)

dat <- dat %>%
  mutate(days = dmy(days))

You can also try wrapping days in an as.character() function to get it out of factor mode.

4 Likes

This topic was automatically closed 7 days after the last reply. New replies are no longer allowed.