R-使用“应用"而不是嵌套循环的基本理解 [英] R - Basic understanding of using 'apply' instead of nested loop

查看:64
本文介绍了R-使用“应用"而不是嵌套循环的基本理解的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

因此,我是R语言的新手(我来自Python背景),在理解如何/何时实现 apply 函数(lapply,sapply,rapply等)而不是理解时,我仍然遇到一些问题嵌套循环.

So I am new to R (I come from a Python background) and I am still having some issues understanding how/when to implement apply functions (lapply, sapply, rapply, etc) instead of nested loops.

作为示例,假设您想执行一些功能FUN,将列表中的每个元素与另一个列表中的每个元素进行比较.我会写一些类似的东西:

As an example, suppose you wanted to perform some function FUN that compared each element of list to each element of another list. I would write something along the lines of:

n = 1
m = 1
sameList = NULL
for(i in 1:length(list1)){
    for(j in 1:length(list2)){
        if(list1[n]==list2[m]){
            sameList<-c(sameList, list1[n]}
    n = n+1
    }
m = m+1
}

换句话说,是一个嵌套的循环,遍历每个列表的每个元素.

In other words, some nested loop that iterates over every element of each list.

我正在学习的是,在R中连接列表中间循环是一个非常低效的过程,这就是为什么使用 apply 的原因.

What I am learning is that concatenating a list mid-loop is a very inefficient process in R, which is why apply is used.

那么将如何使用 apply (或其任何版本)替换上面的示例代码?

So how would apply (or any version of it) be used to replace the above example code?

推荐答案

要使用 lapply ,您可以运行:

sameList = lapply(list1, function(x) lapply(list2, function(y) if (x==y) x else NULL))

这篇关于R-使用“应用"而不是嵌套循环的基本理解的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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