regents
regents

Reputation: 626

Change dates on a list of dataframes

I have a list of dataframe with 8 variables in each of 6 dataframes. The 5th variable is a date and I would like to convert it from class character to a Date using lubridate. The date is in the form dd-mmm-yy. Currently I am using

firstOfMonth <- lapply(fileList,function(x) { x[5] <-
as.Date(strftime(x, format="%d-%b-y"))

})

but am getting the following error.

Error in as.POSIXlt.default(x, tz = tz) : 

do not know how to convert 'x' to class “POSIXlt”

Additionally, I would like to change the class of the 8th column to numeric. The following has not been successful.

lapply(listDF, function(df) mutate_at(df, vars(matches("^Amount")), as.numeric))

Name    Address City    District    Date    Visit   Completed   Amount
Baxter  1211 South Ave  Akron   A   4-Mar-22    Y   Y   12.02
Christ  105 Main Str    Akron   B   4-Mar-22    Y   N   0
Matthews    152 5th Str Akron   A   4-Mar-22    N   N   0
James   45 River Rd Akron   C   4-Mar-22    Y   Y   24.25
Lewis   92 Washington Str   Akron   D   4-Mar-22    Y   Y   16.5

Upvotes: 2

Views: 599

Answers (1)

akrun
akrun

Reputation: 887571

The format for as.Date should be

as.Date(x, format="%d-%b-%y") #note the `y` in the OP's code

In addition to that, there is only assignment of the 5th column to Date column, but it is not returning the x i.e. the data.frame

lapply(fileList,function(x) { 
      x[,5] <- as.Date(x[,5], format="%d-%b-%y");
   x})

This could be done more easily with transform (where we are changing multiple columns)

lapply(fileList, transform, Date = as.Date(Date, format = "%d-%b-%y"),
       Amount = as.numeric(as.character(Amount))))

Also, it is not clear whether the 'Amount' is factor class or not. If it is just character class, remove the as.character


With tidyverse, this can be done using map (from purrr) and mutate (from dplyr)

library(tidyverse)
map(fileList, ~ .x %>%
                  mutate(Date = dmy(Date),
                         Amount = as.numeric(as.character(Amount))))

Upvotes: 3

Related Questions