我有两个集合:A包含x,y两列,B也包含x,y两列。
我需要找到A中那些行的索引在B中也存在(x和y必须匹配)。
我想出了一个简单的解决方案(见下文),但是这个比较操作在循环内部,并且paste
会增加更多的额外时间。
B <- data.frame(x = sample(1:1000, 1000), y = sample(1:1000, 1000))
A <- B[sample(1:1000, 10),]
#change some elements
A$x[c(1,3,7,10)] <- A$x[c(1,3,7,10)] + 0.5
A$xy <- paste(A$x, A$y, sep='ZZZ')
B$xy <- paste(B$x, B$y, sep='ZZZ')
indx <- which(A$xy %in% B$xy)
indx
例如,对于单个观察值,
paste
的替代方法快了近3倍。 ind <- sample(1:1000, 1)
xx <- B$x[ind]
yy <- B$y[ind]
ind <- which(with(B, x==xx & y==yy))
# [1] 0.0160000324249268 seconds
xy <- paste(xx,'ZZZ',yy, sep='')
ind <- which(B$xy == xy)
# [1] 0.0469999313354492 seconds
data.table
包可能会提供解决方案。对于许多匹配和索引类型操作,它比其他方法快得多。 - Josh O'Brien