簡體   English   中英

匹配從一個數據集到參考數據集(R)的行

[英]Matching rows from one dataset to a reference dataset (R)

我有個問題。 假設我有兩個數據幀。

values    <-   data.frame(x = rnorm(10000), y = rnorm(10000), matches = 0)
reference <-   data.frame(a = rnorm(10000), b = rnorm(10000))

對於“值”中的每一行,我想知道在定義范圍內的“參考”數據集中有多少匹配。

system.time(

for (i in 1:nrow(values))
{  
# defining valid range    
x1 <- values$x[i] - 0.1 
x2 <- values$x[i] + 0.1
y1 <- values$y[i] - 0.2
y2 <- values$y[i] + 0.2

#matching values versus reference dataset
values$matches[i] <- nrow(reference[reference$a %between% c(x1,x2) & reference$b %between% c(y1,y2),])
}

)


user  system elapsed 
9.91    0.03    9.94 

上面的示例是有用的,但對於大型數據集,它需要很長時間。 也許這可以用data.table完成嗎?

先感謝您

這是一個data.table方法:

# set of data.tables
values    <-   setDT(data.frame(x = rnorm(10000), y = rnorm(10000), matches = 0))
reference <-   setDT(data.frame(a = rnorm(10000), b = rnorm(10000)))
# calculate sum of ranges, initialize matches variable as integer for speed
values[, matches := integer(nrow(values))]

values[, matches := sum(reference$a %between% c(x-0.1, x+0.1) * 
                        reference$b %between% c(y-0.2, y+0.2)), by=rownames(values)]

它可能比你擁有的更快,盡管可能有更快的方法。

這是使用dplyr的rowwise()的另一種解決方案。 如果“定義的范圍”是對稱的,則可以通過僅檢查兩個條件來提高性能:

count_matches <- function(x, y) {
    sum(abs(reference$a - x) <= 0.1 & abs(reference$b - y) <= 0.2)
}

library(dplyr)
values %>%
  rowwise() %>%
  mutate(matches = count_matches(x, y))

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM