【发布时间】:2021-03-22 07:11:33
【问题描述】:
我正在尝试对 data.table 的多个数字和因子列进行分组。 这是一些数据:
library(data.table)
dt <- data.table(Zeit = c(117.9, 118, 118, 118, 118.1, 118.1, 118.2, 118.2, 118.2, 118.3, 118.3),
a = factor(c(15, 15, 1, 0, 0, 0, 1, 1, 15, 15, 15)),
b = factor(c(1, 1, 1, 0, 0, 0, 1, 1, 1, 1, 1)))
我正在使用这个功能:
compr_uniq_data <- function(ecuData) {
ecuData <- ecuData[, lapply(.SD, function(x) if (is.numeric(x)) mean(x, na.rm = TRUE)
else unlist(unique(x[!is.na(x)]))), by = Zeit]
return(ecuData)
}
compr_uniq_data(dt)
但我收到以下错误:
Supplied 2 items for column 2 of group 2 which has 3 rows. The RHS length must either be 1 (single values are ok) or match the LHS length exactly. If you wish to 'recycle' the RHS please use rep() explicitly to make this intent clear to readers of your code.
我做错了什么? 如果我只使用一个因子列,它就可以工作。
预期的结果应该是这样的:
dtres <- data.table(Zeit = c(117.9, 118, 118, 118, 118.1, 118.2, 118.2, 118.3),
a = c(15, 15, 1, 0, 0, 1, 15, 15),
b = c(1, 1, 1, 0, 0, 1, 1, 1))
【问题讨论】:
标签: r data.table grouping