不适用日期与data.table

时间:2018-07-02 07:49:09

标签: r date data.table na lubridate

我有一个数据表。

require(data.table)
require(lubridate)
testDT <- data.table(dateA = c(NA,NA), dateB = c(ymd("20110101"),ymd("20100101")))
testDT
#       dateA      dateB
#    1:    NA 2011-01-01
#    2:    NA 2010-01-01

我想执行以下操作:如果dateA为NA,则使用与dateB中相同的值。我尝试了以下命令:

> testDT[is.na(dateA), dateA := dateB]
Warning message:
In `[.data.table`(testDT, is.na(dateA), `:=`(dateA, dateB)) :
  Coerced 'double' RHS to 'logical' to match the column's type; may have truncated precision. Either change the target column ['dateA'] to 'double' first (by creating a new 'double' vector length 2 (nrows of entire table) and assign that; i.e. 'replace' column), or coerce RHS to 'logical' (e.g. 1L, NA_[real|integer]_, as.*, etc) to make your intent clear and for speed. Or, set the column type correctly up front when you create the table and stick to it, please.

如您所见,出现警告,结果很奇怪:

> testDT
   dateA      dateB
1:  TRUE 2011-01-01
2:  TRUE 2010-01-01

为什么不起作用?

P.S。我知道我们可以使用:

> testDT[,dateA := ifelse(is.na(dateA), dateB, dateA)]
> testDT
   dateA      dateB
1: 14975 2011-01-01
2: 14610 2010-01-01
> testDT[,dateA := as.Date(dateA, origin = "1970-01-01")]
> testDT
        dateA      dateB
1: 2011-01-01 2011-01-01
2: 2010-01-01 2010-01-01

2 个答案:

答案 0 :(得分:1)

您收到该警告消息是因为dateA列的类别不正确(@ Emmanuel-Lin已经提到过):

> str(testDT)
Classes ‘data.table’ and 'data.frame':    2 obs. of  2 variables:
 $ dateA: logi  NA NA
 $ dateB: Date, format: "2011-01-01" "2010-01-01"
 - attr(*, ".internal.selfref")=<externalptr>

可能的解决方案是首先使用dateA的内置日期函数将as.Date列转换为日期类:

# convert 'dateA'-column to 'Date'- class first
testDT[, dateA := as.Date(dateA)]   # alternatively: as.IDate(dateA)

# fill the 'NA' values in the 'dateA'-column
testDT[is.na(dateA), dateA := dateB][]

给出:

> testDT
        dateA      dateB
1: 2011-01-01 2011-01-01
2: 2010-01-01 2010-01-01

答案 1 :(得分:0)

由于第一列中仅包含NA,因此它会猜测是逻辑的。

如果添加一个不是NA的元素,则效果很好:

您的示例还包含一个元素

library(ggeffects)
library(sjmisc) # to preserve labels
data(efc)

# prepare data, create binary outcome and make
# numeric variables categorical
efc$neg_c_7d <- dicho(efc$neg_c_7)
efc$c161sex <- to_factor(efc$c161sex)
efc$c172code <- to_factor(efc$c172code)

# fit logistic regression
m <- glm(
  neg_c_7d ~ c12hour + c161sex * c172code,
  data = efc,
  family = binomial(link = "logit")
)

# compute and plot marginal effects
ggpredict(m, c("c172code", "c161sex")) %>% plot()

结果:

require(data.table)
require(lubridate)
testDT <- data.table(dateA = c(NA,NA, ymd("20110101")), dateB = c(ymd("20110101"),ymd("20100101"), ymd("20100101")))

testDT[is.na(dateA), dateA := dateB]

那你为什么只有NA?