【问题标题】:Why is data.table not making a data.table from a table although data.frame does?为什么 data.table 没有从表中创建 data.table,尽管 data.frame 可以?
【发布时间】:2015-02-13 12:11:29
【问题描述】:

我有以下数据和代码:

mydf
  grp categ condition value
1   A     X         P     2
2   B     X         P     5
3   A     Y         P     9
4   B     Y         P     6
5   A     X         Q     4
6   B     X         Q     5
7   A     Y         Q     8
8   B     Y         Q     2
> 
> 
mydf = structure(list(grp = structure(c(1L, 2L, 1L, 2L, 1L, 2L, 1L, 
2L), .Label = c("A", "B"), class = "factor"), categ = structure(c(1L, 
1L, 2L, 2L, 1L, 1L, 2L, 2L), .Label = c("X", "Y"), class = "factor"), 
    condition = structure(c(1L, 1L, 1L, 1L, 2L, 2L, 2L, 2L), .Label = c("P", 
    "Q"), class = "factor"), value = c(2, 5, 9, 6, 4, 5, 8, 2
    )), .Names = c("grp", "categ", "condition", "value"), out.attrs = structure(list(
    dim = structure(c(2L, 2L, 2L), .Names = c("grp", "categ", 
    "condition")), dimnames = structure(list(grp = c("grp=A", 
    "grp=B"), categ = c("categ=X", "categ=Y"), condition = c("condition=P", 
    "condition=Q")), .Names = c("grp", "categ", "condition"))), .Names = c("dim", 
"dimnames")), row.names = c(NA, -8L), class = "data.frame")

但是,以下适用于 data.frame 但不适用于 data.table:

> data.frame(with(mydf, table(grp, categ, condition)))
  grp categ condition Freq
1   A     X         P    1
2   B     X         P    1
3   A     Y         P    1
4   B     Y         P    1
5   A     X         Q    1
6   B     X         Q    1
7   A     Y         Q    1
8   B     Y         Q    1
> 
> data.table(with(mydf, table(grp, categ, condition)))
   V1
1:  1
2:  1
3:  1
4:  1
5:  1
6:  1
7:  1
8:  1
> 

我在这里犯了一些错误还是我需要更正 data.table 命令以获取其他变量?这里极不可能有错误。使用 2 个变量,它可以正常工作:

> data.table(with(mydf, table(grp, categ)))
   categ grp N
1:     A   X 2
2:     B   X 2
3:     A   Y 2
4:     B   Y 2
> 
> 
> data.frame(with(mydf, table(grp, categ)))
  grp categ Freq
1   A     X    2
2   B     X    2
3   A     Y    2
4   B     Y    2

感谢您的帮助。

【问题讨论】:

  • 似乎as.data.table(with(mydf, table(grp, categ, condition))) 有效,但我不确定为什么只有data.table 无效。我猜想arrays 中存在data.frame 的一些方法,而data.table 中不存在这种方法,因为在您的第一个示例中,与第二个示例相比,它是array。您也可以执行Res <- setDT(data.frame(with(mydf, table(grp, categ, condition)))) 之类的操作,尽管它仍然无法回答问题。
  • data.table 仅对矩阵或 data.frame 输入调用 as.data.tabledata.frame 调用 as.data.frame 也用于其他输入。
  • 你应该在 github 上提交错误报告 - 存在 as.data.table.tabledata.table 没有委托给它; fwiw 我几乎总是使用 as.data.table 在类型之间进行转换 - 它通常更快

标签: r dataframe data.table


【解决方案1】:

在 data.table v1.9.5 的 commit #1760 中修复。关闭#1043

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2012-11-17
    • 1970-01-01
    • 1970-01-01
    • 2016-03-01
    • 2013-04-15
    • 2017-06-14
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多