【问题标题】:Using apply family of functions to replace nested for loop in R使用 apply 系列函数替换 R 中的嵌套 for 循环
【发布时间】:2015-07-25 14:50:20
【问题描述】:

我写了一个接受 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 会起作用吗?

【问题讨论】:

    标签: r apply


    【解决方案1】:

    您可以像使用循环一样使用apply 函数,但语法不同

    dummy <- function(x, y) paste(x, y)
    sapply(1:4, function(i) sapply(1:4, function(j) dummy(nfl_teams[i], years[j])))
    

    【讨论】:

    • 由于这些字符向量的长度相同,所以这里也可以使用Map函数来达到同样的效果。类似于Map(dummy, nfl_teams, years)
    【解决方案2】:

    如果您的download_data 函数使用nfl_teamsyears 来构造从中提取数据的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。如果可能的话,这是我想要摆脱的重复绑定。

    【讨论】:

    • 循环并绑定到 DF 正是我正在做的事情。这看起来是一种更好的方法,感谢您的帮助。
    【解决方案3】:

    另一种方法是将对象强制为列表,并避免嵌套 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"
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2015-08-08
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多