我有一個包含 1.6 億行和 2 列(材料名稱和價格)的資料框。我想確定價格出現的頻率。
例如,
10 美元的價格被給出了 100 次不同的時間。我想按從最大到最小的順序對值進行排序(例如,100 美元被給予 1000 次)
有 2,484,557 個唯一價格,因此“表格”不是最有用的解決方案。
我的問題是我正在處理記憶體問題。
有什么建議我可以如何做到這一點?
uj5u.com熱心網友回復:
這是一個 2 GB 的資料框,有 1.6 億行和大約 300 萬個唯一價格:
set.seed(42)
n = 160E6
fake_data <- data.frame(material = sample(LETTERS, n, replace = TRUE),
price = sample(1:3E6, n, replace = TRUE))
我喜歡dplyr語法,但對于具有許多組的大資料,data.table并collapse提供更好的性能。
我們可以使用dtplyr將 dplyr 代碼轉換為 data.table。這在我的機器上需要 22 秒,結果顯示每個價格在資料中出現的次數。
library(dplyr)
library(dtplyr)
fake_data %>%
lazy_dt() %>%
count(price, sort = TRUE)
結果
Source: local data table [3,000,000 x 2]
Call: `_DT2`[, .(n = .N), keyby = .(price)][order(desc(n))]
price n
<int> <int>
1 2586972 97
2 2843789 95
3 753207 92
4 809482 92
5 1735845 92
6 809659 90
# … with 2,999,994 more rows
如果您需要更高的性能并且不介意啟發式方法,您還可以對資料進行采樣以使其大 10% 或 1%;如果任何占位符值在整個資料中頻繁出現,它們也很可能在隨機樣本中頻繁出現。
uj5u.com熱心網友回復:
我可能會創建價格區間,例如 0-50 美元、51-100 美元、101-150 美元等。
編輯:更全面的解決方案
library(tidyverse)
df <- letters %>%
expand_grid(., .) %>%
rename(v1 = `....1`,
v2 = `....2`) %>%
mutate(name = paste0(v1, v2)) %>%
select(name) %>%
bind_rows(., ., ., .)
df
n <- nrow(df)
df <- df %>%
mutate(price = rnorm(n = n, mean = 1000, sd = 200))
df %>%
ggplot(aes(x = price))
geom_histogram()
df <- df %>%
mutate(price_grp = case_when(price < 500 ~ "$0-500",
price > 500 & price <= 1000 ~ "$501-1000",
price > 1000 & price <= 1500 ~ "$1001-1500",
price > 1500 ~ " $1500"))
df %>%
group_by(price_grp) %>%
summarize(occurences = n()) %>%
arrange(desc(occurences))
轉載請註明出處,本文鏈接:https://www.uj5u.com/qukuanlian/488565.html
標籤:r
上一篇:在ggplot2中,指定用于geom_smooth()置信區間的值(類似于geom_errorbar)
下一篇:繪制多列、按日期分組和調整比例
