更改数据框列表中的日期

问题描述 投票:1回答:1

我有一个数据帧列表,每个数据帧有8个变量。第五个变量是一个日期,我想使用lubridate将它从类字符转换为日期。日期格式为dd-mmm-yy。目前我正在使用

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

})

但我收到以下错误。

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

不知道如何将'x'转换为类“POSIXlt”

另外,我想将第8列的类更改为数字。以下未成功。

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
r list lapply lubridate
1个回答
2
投票

as.Date的格式应该是

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

除此之外,只有第5列到Date列的分配,但它没有返回x,即data.frame

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

使用transform(我们正在更改多个列)可以更轻松地完成此操作

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

此外,尚不清楚'金额'是否是factor类。如果它只是character类,删除as.character


使用tidyverse,可以使用map(来自purrr)和mutate(来自dplyr)来完成

library(tidyverse)
map(fileList, ~ .x %>%
                  mutate(Date = dmy(Date),
                         Amount = as.numeric(as.character(Amount))))
© www.soinside.com 2019 - 2024. All rights reserved.