【发布时间】:2015-12-09 17:51:26
【问题描述】:
在 R 中,我怎样才能最好地矢量化这个操作?
我有一个参考值表,有一个下限 (A) 和上限 (B)。
我还有一个值表 (X) 可以对照上表进行查找。
对于 X 的每个值,我需要确定它是否位于参考表中 A 和 B 的任何值之间。
为了演示以上内容,这里有一个使用循环的解决方案:
#For Reproduceability,
set.seed(1);
#Set up the Reference and Lookup Tables
nref = 5; nlook = 10
referenceTable <- data.frame(A=runif(nref,min=0.25,max=0.5),
B=runif(nref,min=0.50,max=0.75));
lookupTable <- data.frame(X=runif(nlook),IsIn=0)
#Process for each row in the lookup table
#search for at least one match in the reference table where A <= X < B
for(x in 1:nrow(lookupTable)){
v <- lookupTable$X[x]
tmp <- subset(referenceTable,v >= A & v < B)
lookupTable[x,'IsIn'] = as.integer(nrow(tmp) > 0)
}
我正在尝试删除 for(x in .... ) 组件,因为我现实生活中的问题表有成千上万条记录。
【问题讨论】:
-
这样的问题在 SO 上被问了很多次。请搜索
data.table::foverlaps或 BioconductorIRanges包。 -
@DavidArenburg 如果
apply()函数在这里不是一个好的选择(不比原来的for循环更好),那么什么是好的选择? -
我建议
findInterval在这里可能会有所帮助,但明天之前没有时间发布解决方案。例如?findInterval或stackoverflow.com/questions/31478022/… 和stackoverflow.com/questions/34047920/… -
Nice answer in a related Q&A。请注意
pos2 := pos步骤以创建单个值的“范围”。
标签: r vectorization lookup