更改数据框列表上的日期
Change dates on a list of dataframes
我有一个数据框列表,其中 6 个数据框各有 8 个变量。第 5 个变量是日期,我想使用 lubridate 将它从 class 字符转换为日期。日期的格式为 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' 转换为 class “POSIXlt”
此外,我想将第 8 列的 class 更改为数字。以下未成功。
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
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))))
另外,不清楚'Amount'是不是factor
class。如果只是 character
class,删除 as.character
使用 tidyverse
,可以使用 map
(来自 purrr
)和 mutate
(来自 dplyr
)
library(tidyverse)
map(fileList, ~ .x %>%
mutate(Date = dmy(Date),
Amount = as.numeric(as.character(Amount))))
我有一个数据框列表,其中 6 个数据框各有 8 个变量。第 5 个变量是日期,我想使用 lubridate 将它从 class 字符转换为日期。日期的格式为 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' 转换为 class “POSIXlt”
此外,我想将第 8 列的 class 更改为数字。以下未成功。
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
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))))
另外,不清楚'Amount'是不是factor
class。如果只是 character
class,删除 as.character
使用 tidyverse
,可以使用 map
(来自 purrr
)和 mutate
(来自 dplyr
)
library(tidyverse)
map(fileList, ~ .x %>%
mutate(Date = dmy(Date),
Amount = as.numeric(as.character(Amount))))