这是一个关于tidyr的方法:
library(tidyverse)
library(magrittr)
example_data <- matrix(
c(293994,8,3,
293994,5,3,
949859,2,1,
949859,1,1,
123234,1,1,
123234,3,1,
123234,4,1),
ncol = 3,
byrow = TRUE) %>%
as.data.frame %>%
set_colnames(c('userid','productid','freq'))
spread(example_data, key = productid, value = freq, fill = 0)
spread
操作比基本的 R table
操作快得多,但在大规模数据处理时,data.table
又会轻松胜过 tidyr
/ dplyr
。然而,正如前面的回答所指出的那样,data.table 的等价操作 dcast
并不能正常工作。这似乎是一个已知问题,不幸的是,它仍未得到解决。
我尝试了在大规模数据(200万条记录)上使用 tidyr
方法,但无法在我的本地机器上运行。因此,您需要将其分割(然后使用 rbind
),或者将其传输到集群中(使用 rhadoop
或 sparklyr
)。
尽管如此,下面提供了可重现的“大数据”示例代码,以便其他人可以添加一些内容。
randomkey <- function(digits){
paste(sample(LETTERS, digits, replace = TRUE), collapse = '')
}
products <- replicate(10, randomkey(20)) %>% unique
customers <- replicate(500000, randomkey(50)) %>% unique
big_example_data <- data.frame(
useruid = rep(sample(customers, length(customers), replace = FALSE), 4),
productid = sample(products, replace = TRUE),
freq = sample(1:5)
)
dim(big_example_data)
head(big_example_data)
system.time(
big_matrix <- spread(big_example_data, key = productid, value = freq, fill = 0)
)
aggregate(freq ~ userid + productid,data = df,sum)
吗? - Andy Cliftonlibrary(tidyr); spread(x,productid,freq,fill = 0)
。 - AndrewMacDonald