【发布时间】:2013-04-02 18:23:42
【问题描述】:
我刚刚在我的脚本中发现了这个有点奇怪的警告。
# Warning message:
# In rbindlist(list(DT.1, DT.2)) : NAs introduced by coercion
观察 1:这是一个可重现的示例:
require(data.table)
DT.1 <- data.table(x = letters[1:5], y = 6:10)
DT.2 <- data.table(x = LETTERS[1:5], y = 11:15)
# works fine
rbindlist(list(DT.1, DT.2))
# x y
# 1: a 6
# 2: b 7
# 3: c 8
# 4: d 9
# 5: e 10
# 6: A 11
# 7: B 12
# 8: C 13
# 9: D 14
# 10: E 15
但是,现在如果我将列 x 转换为 factor(是否有序)并执行相同操作:
DT.1[, x := factor(x)]
rbindlist(list(DT.1, DT.2))
# x y
# 1: a 6
# 2: b 7
# 3: c 8
# 4: d 9
# 5: e 10
# 6: NA 11
# 7: NA 12
# 8: NA 13
# 9: NA 14
# 10: NA 15
# Warning message:
# In rbindlist(list(DT.1, DT.2)) : NAs introduced by coercion
但是rbind 做得很好!
rbind(DT.1, DT.2) # where DT.1 has column x as factor
# do.call(rbind, list(DT.1, DT.2)) # also works fine
# x y
# 1: a 6
# 2: b 7
# 3: c 8
# 4: d 9
# 5: e 10
# 6: A 11
# 7: B 12
# 8: C 13
# 9: D 14
# 10: E 15
如果列x 也是ordered factor,则可以重现相同的行为。由于帮助页面?rbindlist 显示:Same as do.call("rbind",l), but much faster.,我猜这不是我们想要的行为?
这是我的会话信息:
# R version 3.0.0 (2013-04-03)
# Platform: x86_64-apple-darwin10.8.0 (64-bit)
#
# locale:
# [1] en_US.UTF-8/en_US.UTF-8/en_US.UTF-8/C/en_US.UTF-8/en_US.UTF-8
#
# attached base packages:
# [1] stats graphics grDevices utils datasets methods base
#
# other attached packages:
# [1] data.table_1.8.8
#
# loaded via a namespace (and not attached):
# [1] tools_3.0.0
编辑:
观察 2: 继@AnandaMahto 的另一个有趣观察后,颠倒顺序:
# column x in DT.1 is still a factor
rbindlist(list(DT.2, DT.1))
# x y
# 1: A 11
# 2: B 12
# 3: C 13
# 4: D 14
# 5: E 15
# 6: 1 6
# 7: 2 7
# 8: 3 8
# 9: 4 9
# 10: 5 10
在这里,来自DT.1 的列被默默地强制转换为numeric。
编辑: 澄清一下,这与rbind(DT2, DT1) 的行为相同,其中 DT1 的列 x是一个因素。 rbind 似乎保留了第一个参数的类。我将把这部分留在这里,并提到在这种情况下,这是所需的行为,因为rbindlist 是rbind 的更快实现。
观察 3: 如果现在,两列都转换为因子:
# DT.1 column x is already a factor
DT.2[, x := factor(x)]
rbindlist(list(DT.1, DT.2))
# x y
# 1: a 6
# 2: b 7
# 3: c 8
# 4: d 9
# 5: e 10
# 6: a 11
# 7: b 12
# 8: c 13
# 9: d 14
# 10: e 15
这里,来自DT.2 的列x 丢失(/ 替换为DT.1 的列)。如果顺序颠倒,则会发生完全相反的情况(DT.1 的 x 列被 DT.2 的 x 列替换)。
一般来说,处理rbindlist 中的factor 列似乎存在问题。
【问题讨论】:
标签: r data.table