简体   繁体   English

优化 R 中的双循环

[英]Optimise a double loop in R

I have this double loop working:我有这个双循环工作:

for (i in 1:nrow(doe)) {
  for (j in 1:nrow(rsm)) {
    if (rsm[j,2] == doe[i,2] & rsm[j,3] == doe[i,3] & rsm[j,4] == doe[i,4]) {
      out <- cbind(doe[i,6], rsm[j,6])
      matching_out <- rbind(matching_out, out)
      break
    }
  }
}

As you can see, I have to match three columns together in two dataset (# 2, 3, 4 in this case), and then cbind column 6 of the two data frame in another one.如您所见,我必须将两个数据集中的三列匹配在一起(在这种情况下为 # 2, 3, 4),然后将两个数据框的第 6 列cbind在另一个数据集中。

The question is: since this is quite slow, how can I optimise it?问题是:由于这很慢,我该如何优化它? I suppose I could use an apply -like approach, but I can't figure out.我想我可以使用类似apply的方法,但我想不通。

您可以简单地使用基本R单线执行此操作:

merge(rsm, doe, by.x=names(rsm)[2:4],by.y=names(doe)[2:4])[-(1:3)]

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM