使用 apply 系列函数替换 R 中的嵌套 for 循环 [英] Using apply family of functions to replace nested for loop in R
问题描述
我写了一个接受 3 个参数的函数:
I wrote a function that takes 3 arguments:
download_data <- function(team, year, df) {
...
}
我想用两个字符向量分别为上述函数提供第一个和第二个参数,以便向量的每个组合被调用一次:
I have two character vectors that I want to use to provide the first and second argument respectively to the above function, so that each combination of the vectors is called once:
nfl_teams <- c("bills", "dolphins", "jets", "patriots")
years <- c("2002", "2003", "2004", "2005")
我可以使用嵌套的 for 循环很容易地做到这一点:
I can do so fairly easily using a nested for loop:
for (i in 1:4) {
for ( j in 1:4) {
salary_data <- download_data(nfl_teams[i], years[j], salary_data)
}
}
然而,这似乎是一个un-R"方法来实现这一点,最好使用 apply
函数之一.然而,在阅读并尝试了所有这些之后,我无法完成这个看似简单的任务.
However, it seems that this an "un-R" way to accomplish this, and it would be better to use one of the apply
functions. However, after reading through all of them and trying them out, I was unable to accomplish this seemingly simple task.
看起来这可能是一个矩阵,因此 apply
会起作用吗?
It seems like maybe this would be a matrix, thus apply
would work?
推荐答案
你可以像循环一样使用 apply
函数,除了语法不同
You can use the apply
functions just like loops, except with different syntax
dummy <- function(x, y) paste(x, y)
sapply(1:4, function(i) sapply(1:4, function(j) dummy(nfl_teams[i], years[j])))
这篇关于使用 apply 系列函数替换 R 中的嵌套 for 循环的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!