避免使用for循环 [英] Avoid the use of for loops

查看:131
本文介绍了避免使用for循环的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在使用R,并且我有这样的代码:

I'm working with R and I have a code like this:

for (i in 1:10)
   for (j in 1:100)
        if (data[i] == paths[j,1])
            cluster[i,4] <- paths[j,2]

其中:

  • data是具有100行和1列的向量
  • paths是一个100行5列的矩阵
  • cluster是一个100行5列的矩阵
  • data is a vector with 100 rows and 1 column
  • paths is a matrix with 100 rows and 5 columns
  • cluster is a matrix with 100 rows and 5 columns

我的问题是:如何避免使用"for"循环遍历矩阵?我不知道apply函数(lapplytapply ...)在这种情况下是否有用.

My question is: how could I avoid the use of "for" loops to iterate through the matrix? I don't know whether apply functions (lapply, tapply...) are useful in this case.

例如,当使用j=10000时,这是一个问题,因为执行时间很长.

This is a problem when j=10000 for example, because execution time is very long.

谢谢

推荐答案

我认为可以使用以下方式对两个循环进行矢量化处理:

I think that both loops can be vectorized using the following:

cluster[na.omit(match(paths[1:100,1],data[1:10])),4] = paths[!is.na(match(paths[1:100,1],data[1:10])),2]

这篇关于避免使用for循环的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆