Search code examples
rdatevectoratomic

Changing data in R to dates


I am attempting to change values in my data set to Dates, however I get the error code form y code;

>WC1$date <- as.Date(WC1[X,], format= "%m/%d/%Y")

Error in as.Date(WC1[X, ], format = "%m/%d/%Y") : object 'X' not found
Error in WC1["X", ] : subscript out of bounds

Currently this is what my data looks like.

      X                    X1.2.2018 X1.3.2018 X1.4.2018 X1.5.2018 X1.8.2018
 [1,] "ED"                 NA        NA        NA        NA        NA       
 [2,] "Front Clinic "      NA        NA        NA        NA        NA  

Even if I transpose my data and attempt with a similar approach. In the CSV file my data does not have X's in front of the dates so I'm not sure as to why they appear that way in R. Also I have tried using date format and get the same error.

> WC1$date <- as.Date(WC1['X',], format= "%m.%d.%Y")
Error in WC1["X", ] : subscript out of bounds

Solution

  • The values (X, X1.2.2018, X1.3.2018, X1.4.2018, X1.5.2018, X1.8.2018) are already set as column names (i.e. headers) so they are not the "first row", R makes a distinction between these that you don't have in Excel. This means that you can't select the values using [] but can use names().

    First remove the leading X with gsub, then format the dates using as.Date

    names(WC1)<-gsub("[^0-9\\.]", "", names(WC1))
    names(WC1)<-as.Date(names(WC1), format = "%m.%d.%Y")
    

    Alternatively, the addition of X to the beginning of your column names is a behaviour you can toggle in your read.csv() command when reading in the file in the first place (see: R- Why are Xs added to the names of variables in my data frame?)