[英]How to replace mutiple nested for loops with apply family functions in R?
[英]Using apply family of functions to replace nested for loop in R
我寫了一個接受 3 個參數的函數:
download_data <- function(team, year, df) {
...
}
我有兩個字符向量,我想用它們分別為上述函數提供第一個和第二個參數,以便向量的每個組合被調用一次:
nfl_teams <- c("bills", "dolphins", "jets", "patriots")
years <- c("2002", "2003", "2004", "2005")
我可以使用嵌套的 for 循環很容易地做到這一點:
for (i in 1:4) {
for ( j in 1:4) {
salary_data <- download_data(nfl_teams[i], years[j], salary_data)
}
}
但是,這似乎是實現此目的的“un-R”方式,最好使用其中一個apply
函數。 然而,在閱讀並嘗試了所有這些之后,我無法完成這個看似簡單的任務。
看起來這可能是一個矩陣,因此apply
會起作用嗎?
您可以像循環一樣使用apply
函數,但語法不同
dummy <- function(x, y) paste(x, y)
sapply(1:4, function(i) sapply(1:4, function(j) dummy(nfl_teams[i], years[j])))
如果您的download_data
函數使用nfl_teams
和years
來構建從中提取數據的 URL,我會推薦這樣的方法:
URL <- expand.grid(nfl_teams = c("bills", "dolphins", "jets", "patriots"),
years = c("2002", "2003", "2004", "2005"),
stringsAsFactors = FALSE)
URL$url <- paste0(...) # build your url string here
salary_data <- lapply(URL$url, download_data)
salary_data <- do.call("rbind", salary_data)
這種方法假設您將download_data
每次迭代綁定到現有的salary_data
。 如果可能的話,這是我想要擺脫的重復綁定。
另一種方法是將對象強制為列表,並避免嵌套的apply
系列函數。
unlist(lapply(as.list(nfl_teams), function(x) dummy(x, years) ))
[1] "bills 2002" "bills 2003" "bills 2004" "bills 2005"
[5] "dolphins 2002" "dolphins 2003" "dolphins 2004" "dolphins 2005"
[9] "jets 2002" "jets 2003" "jets 2004" "jets 2005"
[13] "patriots 2002" "patriots 2003" "patriots 2004" "patriots 2005"
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.