【发布时间】:2020-01-18 13:15:35
【问题描述】:
我一直在努力通过获取最后一个元素来聚合 dcast。这是一个例子:
x <- data.table::data.table(foo = "bar", value = c(1, 0))
x
# foo value
# 1: bar 1
# 2: bar 0
data.table::dcast(x, ... ~ foo, fun.aggregate = function(x) x[length(x)])
# Error: Aggregating function(s) should take vector inputs and return a single value (length=1).
# However, function(s) returns length!=1. This value will have to be used to fill any missing
# combinations, and therefore must be length=1. Either override by setting the 'fill' argument
# explicitly or modify your function to handle this case appropriately.
dcast 的 reshape2 版本也会发生这种情况,如果使用 data.frame 而不是 data.table。
我可以通过多种方式让它发挥作用。例如,我可以使用
data.table::dcast(x, ... ~ foo, fun.aggregate = function(x) rev(x)[1L])
# . bar
# 1: . 0
并得到预期的结果。 dplyr::last() 函数也有效,data.table::last() 无效。
但是,我感兴趣的是为什么使用 x[length(x)] 不起作用。如果我将中间打印命令放在聚合函数中以弄清楚发生了什么,我会得到以下信息:
data.table::dcast(x, ... ~ foo,
fun.aggregate = function(x) {print(x); print(length(x)); 5L}, value.var = "value")
# numeric(0)
# [1] 0
# [1] 1 0
# [1] 2
# . bar
# 1: . 5
这表明dcast 正在迭代一个不在表中的foo 值,并且不能存在于其他地方,因为foo 是一个简单的字符向量,而不是因子向量。发生了什么事?
R 版本:3.6.0
data.table 版本:1.12.2
【问题讨论】:
-
你能显示预期的输出吗
-
当然,我已将其添加为使用 rev(x)[1L] 的输出。
-
不是在
dcast中进行,您不能先进行子集化,然后进行 dcast -
我可以,是的,我会回到我的实际用例,看看是否有帮助。问题更多的是为什么使用 x[length(x)] 不能按预期工作。
-
使用
function(x) x[max(length(x), 1)]保证非零长度输出
标签: r data.table reshape2