我正在尋找在兩個資料集之間進行加權連接:
library(tidyverse)
set.seed(1)
test.sample <- data.frame(zip=sample(1:3,50,replace = TRUE))
index.dat <- data.frame(zip=c(1,1,2,3,3,3),
fips=c("A1", "A2", "B", "C1", "C2","C3"),
prob=c(.75,.25,1,.7,.2,.1))
我的預期輸出將是來自索引資料集的加權樣本:
results1 <- c(rep("A1",14),rep("A2",4),rep("B",19,),rep("C1",9),rep("C2",3),"C3")
最終嘗試從總體的概率分布中加入與多個 fips 代碼匹配的郵政編碼。
這條評論很好地描述了我正在努力克服的問題:https : //stackoverflow.com/a/13316857/4828653
這是我提出的一個潛在解決方案,但鑒于我有數十億條記錄,我需要一些性能更高的解決方案。
test_function <- function(x) {
index.dat %>%
filter(zip == x) %>%
sample_n(size=1,weight=prob) %>%
select(fips)
}
results2 <- lapply(test.sample$zip, function(x) test_function(x)) %>%
unlist() %>%
data.frame(fips = .)
> table(results1)
results1
A1 A2 B C1 C2 C3
14 4 19 9 3 1
> table(results2)
results2
A1 A2 B C1 C2 C3
15 3 19 8 2 3
uj5u.com熱心網友回復:
您可以index.dat根據zip, 進行拆分,以給出每個郵政編碼的資料框串列。如果您使用test.sample$zip此串列的子集,您將獲得包含適當郵政編碼的 50 個資料框的串列。然后,您可以使用prob每個資料框列中的權重對 fip 進行采樣。
在你的情況下,這看起來像這樣:
sample_space <- split(index.dat, index.dat$zip)[test.sample$zip]
test.sample$fips <- sapply(sample_space,
function(x) sample(x$fips, 1, prob = x$prob))
現在test.sample$fips將從適當的郵政編碼中隨機選擇一個 fip,并根據相對權重進行采樣。如果我們做一張表test.sampl$fips,我們可以看到比例是正確的:
table(test.sample$fips)
#> A1 A2 B C1 C2
#> 13 5 19 10 3
zip 1 的 18 名成員被分配到 A1 和 A2,(幾乎)以 75:25 的比例分配。正如預期的那樣,zip 2 的所有成員都被賦予了 B,并且 zip 3 的 13 個成員已被適當分配(盡管由于概率較低,沒有選擇 C3)
如果test.sample有 5000 行,我們會看到由于大數定律,這些比例更接近于預期的權重:
#> A1 A2 B C1 C2 C3
#> 1257 419 1687 1153 325 159
轉載請註明出處,本文鏈接:https://www.uj5u.com/net/315228.html
上一篇:根據值獲取名稱列
