Fau*_*lva 1 r dplyr data.table
我正在尝试使用data.table
以获得更好的性能,但不知道如何进行distinct %>% summarize
in的等效操作dplyr
。有什么想法可以使以下代码适应data.table
吗?
group_by_('x,y,z') %>%
distinct('h', .keep_all = TRUE) %>%
summarise(tot1 = sum(value1), tot2 = sum(value2))
Run Code Online (Sandbox Code Playgroud)
您可以使用 2 个步骤进行分组、不同和求和data.table
。首先,使用unique()
与by
参数设置为您的分组和不同的变量。然后summarize()
用分组变量做 data.table 等价物。
dfq = data_frame(
g1 = rep(c('a', 'b', 'c'), times = 12),
g2 = rep(c('d', 'e', 'f', 'g'), times = 9),
c3 = as.integer(30 * runif(36)),
d4 = rep(LETTERS[1:18], times = 2)
)
dtq = as.data.table(dfq)
dtq2 = unique(dtq, by = c("g1", "g2", "d4"))[
, .(sum1 = sum(c3)),
by = c("g1", "g2")
]
Run Code Online (Sandbox Code Playgroud)