【问题标题】:Why does coercing a column in a data.table with by not work while coercing without does work without warning? [duplicate]为什么强制 data.table 中的列不工作,而强制不工作没有警告? [复制]
【发布时间】:2015-01-08 15:52:13
【问题描述】:

下面我用两种方式做同样的操作。第一个不起作用,而第二个起作用。我想知道为什么?我无法通过谷歌在 data.table 文档或其他地方找到这个问题的答案。

SOtable <- data.table(testInt=c(1:100))
SOtable[,testInt := as.double(testInt), by=1:nrow(SOtable)]
##Error in `[.data.table`(SOtable, , `:=`(testInt, as.double(testInt)),  : 
## Type of RHS ('double') must match LHS ('integer'). To check and coerce would impact performance too much for the fastest cases. Either change the type of the target column, or coerce the RHS of := yourself (e.g. by using 1L instead of 1)
SOtable[,testInt := as.double(testInt)]

尝试这样做的原因是因为我想对大 data.table 中的每一行的列进行一些操作,但是一旦我使用 by 我就会得到 LHS/RHS 错误。但是当我输入这个时,我在想:“也许我应该为此使用一些 apply 函数?”

【问题讨论】:

  • 在您的第一个示例中:假设对于第一组,您将 testInt 转换为双变量。在第二组中,您希望它是一个整数变量,您希望将其变成一个双精度变量。这意味着同一个变量应该有两种模式。那是不可能的。 data.table 实际上并不是split 用于by 操作的数据。
  • Aaah @Roland,所以当我使用 by 执行此操作时,它会尝试将每个单独的答案一个一个地写入 data.table(写入一个双精度,而其余的仍然是整数)并且它确实不要先创建一个全新的列来替换旧列。这是有道理的!
  • @Gullydwarf := 通过引用工作,即,它就地修改。

标签: r data.table


【解决方案1】:

@Roland 的回答:

在第一个示例中,您替换了整个列,因此变量类型不是一个因素。 当使用by 时,每个值在计算时都会写入列中,因此如果类型不同,它将尝试(在这种情况下)将双精度变量写入整数列,这将不起作用。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-01-15
    • 2011-02-14
    • 1970-01-01
    • 2012-10-19
    • 2012-04-04
    • 2016-03-21
    相关资源
    最近更新 更多