本文介绍了在没有循环的R中对连续的列表元素对应用函数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我试图找到一种有效的方法(即避免使用循环)来应用一个函数,该函数迭代地将列表的当前和上一个(或下一个)元素作为参数并返回结果的列表(其长度必定短1个元素).作为一个具体的例子,

I am trying to find an efficient (i.e. avoid using loops) way to apply a function that iteratively takes as arguments the current and previous (or next) elements of a list and returns a lists of the result (the length of which will necessarily be 1 element shorter).As a concrete example,

我有一些顶点定义了一些图中的路径

I have a list of vertices defining a path in some graph

vlist <- c(1,2,7,12,17)

来自使用igraph函数"lattice"构造的格子图

which come from a lattice graph constructed using the igraph function "lattice"

G <- graph.lattice(c(5,7))

我想在vlist上应用函数"get.edge.ids",以便返回的列表产生连接vlist中连续元素的边的ID.例如.我想要边缘1-> 2、2-> 7、7-> 12、12-> 17的ID

I want to apply the function "get.edge.ids" over vlist so that the list returned yields the ids of the edges connecting the consecutive elements in vlist.E.g. I want the ids of edges 1-->2, 2-->7, 7-->12, 12-->17

使用for循环这很简单,

This is trivial using a for loop,

    findEids <- function(G,vlist) {
        outlist=c()
        for (i in 1:(length(vlist)-1) {
            outlist=append(outlist,get.edge.ids(G,c(vlist[i],vlist[i+1])))
        }
        return(outlist)
    }

但是我想使用诸如apply()或reduce()之类的矢量化方法来查看是否可以使其更快地工作,因为我需要从脚本中反复调用此类函数(例如,计算G的生成树的总拉伸).

but I would like to use a vectorized approach like apply() or reduce() to see if I can get it to work more quickly since I will need to call functions like this repeatedly from a script (for example, to compute the total stretch for a spanning tree of G).

推荐答案

为此,我使用mapply.例如

a<-1:1000
mapply(function(x,y)x-y,a[-1000],a[-1])

它似乎比for循环版本快一点:

It appears to be slightly faster than the for loop version:

> f <- function(x,y)x-y
> g <- function(){
     o<-c();
     for(i in a[-1000])o<-c(o,f(i,i+1))
> }


>
> system.time(
+     for(i in 1:1000){
+         mapply(f,a[-1000],a[-1])
+     }
+ )
   user  system elapsed
  2.344   0.000   2.345


> system.time(for(i in 1:1000)g())
   user  system elapsed
  3.399   0.000   3.425

这篇关于在没有循环的R中对连续的列表元素对应用函数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

09-03 10:36