【发布时间】:2020-11-15 21:15:23
【问题描述】:
我正在尝试在data.table 中转换多个日期列(具有不同的格式)。目前可用的方法很少。链接Efficiently convert a date column in data.table 之一。我正在尝试使用mapply。但出现以下错误:
[.data.table(df, ,:=((paste0(dtVar, "")) 中的错误, mapply(function(x, : 提供 12 项分配给 6 项 列'X1'。如果您想“回收”RHS,请使用 rep() 来 让代码的读者清楚这一意图。
library(data.table)
# sample data
df <- data.table(
X1 = c("1996-01-04", "1996-01-05", "1996-01-08", "1996-01-09", "1996-01-10", "1996-01-11"),
X2 = c("02/01/1996", "03/01/1996", "04/01/1996", "05/01/1996", "08/01/1996", "09/01/1996"),
stringsAsFactors = FALSE)
# convert date columns
dtVar <- c("X1", "X2")
inDtFmt <- c("%Y-%m-%d","%d/%m/%Y")
df[,(dtVar) := mapply(function(x,y){strptime(df[[x]], format = y)}, dtVar, inDtFmt)]
## Further investigation
mm <- mapply(function(x,y){strptime(df[[x]], format = y)}, dtVar, inDtFmt)
str(mm)
List of 2
# $ X1: POSIXlt[1:6], format: "1996-01-04" "1996-01-05" "1996-01-08" "1996-01-09" ...
# $ X2: POSIXlt[1:6], format: "1996-01-02" "1996-01-03" "1996-01-04" "1996-01-05" ...
谁能告诉我为什么会出现这个错误?
【问题讨论】:
标签: r date data.table