【发布时间】:2015-06-23 17:06:34
【问题描述】:
我在 R 中有一个函数,它将较小的向量与较大的向量进行比较,然后找到匹配的位置并使用该信息从较大的数据帧中提取数据。
compare_masses <- function(mass_lst){
for (i in seq_along(mass_lst)) {
positions <- which(abs(AB_massLst_numeric - mass_lst[i]) < 0.02)
rows <- AB_lst[positions,]
match_df <- rbind(match_df, rows)
}
}
其中mass_lst 是复合质量列表:
例如:mass_lst <- c(315, 243, 484, 121)
AB_massLst_numeric 是较大的群众列表:
例如:AB_massLst_numeric <- c(323, 474, 812, 375, 999, 271, 676, 232)
AB_lst 是一个更大的数据框,我使用位置向量从中提取数据。
match_df 是一个空的数据框我做rbind 的数据。
问题是这个函数里面有一个for循环,即使我使用也需要很长时间
test <- sapply(mass_lst, compare_masses)
所以我的问题是如何使这个函数更快并有可能删除 for 循环?我的数据在现实生活中比我提供的示例要大得多。我想不出一种不迭代来使这个函数工作的方法。
【问题讨论】:
-
你的向量/数据有多大
标签: r performance for-loop sapply