R - 使用“应用"而不是嵌套循环的基本理解 [英] R - Basic understanding of using 'apply' instead of nested loop
问题描述
所以我是 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
,你需要运行:
To use lapply
, you would run:
sameList = lapply(list1, function(x) lapply(list2, function(y) if (x==y) x else NULL))
这篇关于R - 使用“应用"而不是嵌套循环的基本理解的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!