【问题标题】:Change dates on a list of dataframes更改数据框列表上的日期
【发布时间】:2018-04-29 22:18:55
【问题描述】:

我有一个数据框列表,其中 6 个数据框中的每一个中有 8 个变量。第 5 个变量是日期,我想使用 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】:

as.Date 的格式应该是

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

除此之外,仅将第 5 列分配给 Date 列,但它不返回 xdata.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))))

【讨论】:

    猜你喜欢
    • 2021-04-14
    • 2019-01-20
    • 1970-01-01
    • 1970-01-01
    • 2015-04-15
    • 2016-02-19
    • 1970-01-01
    • 2021-02-20
    • 2020-07-18
    相关资源
    最近更新 更多