如何用函数替换r中的这段代码?

时间:2017-11-21 08:44:13

标签: r function

我有这个代码可以工作,但我想学习如何用函数替换它。

library(tidyverse)

l1_1617 <- read.csv("http://www.football-data.co.uk/mmz4281/1617/F1.csv", stringsAsFactors = FALSE)
l1_1516 <- read.csv("http://www.football-data.co.uk/mmz4281/1516/F1.csv", stringsAsFactors = FALSE)
l1_1415 <- read.csv("http://www.football-data.co.uk/mmz4281/1415/F1.csv", stringsAsFactors = FALSE)
l1_1314 <- read.csv("http://www.football-data.co.uk/mmz4281/1314/F1.csv", stringsAsFactors = FALSE)

l1_1617_sel <- l1_1617 %>%
  select(Date:AST) %>%
  mutate(season = 1617)

l1_1516_sel <- l1_1516 %>%
  select(Date:AST) %>%
  mutate(season = 1516)

l1_1415_sel <- l1_1415 %>%
  select(Date:AST) %>%
  mutate(season = 1415)

l1_1314_sel <- l1_1314 %>%
  select(Date:AST) %>%
  mutate(season = 1314)


l1_1317 <- bind_rows(l1_1617_sel, l1_1516_sel, l1_1415_sel, l1_1314_sel)

第一步我尝试了类似的东西,但显然失败了:

dl_l1 <-function(x){
  df_x <- read.csv("http://www.football-data.co.uk/mmz4281/x/F1.csv", stringsAsFactors = FALSE)
}

dl_l1(1617)

2 个答案:

答案 0 :(得分:2)

library(tidyverse)

ids <- as.character(c(1617, 1516, 1415, 1314))

data <- lapply(ids, function(i) {

  read.csv(paste0("http://www.football-data.co.uk/mmz4281/", i ,"/F1.csv"), stringsAsFactors = FALSE) %>%
    select(Date:AST) %>%
    mutate(season = i)

})

data <- do.call(rbind, data)

答案 1 :(得分:0)

我会在函数中创建一个for循环,这样你就可以迭代一个数字向量:

创建函数football,它接受​​一个数字或一个数字向量,然后创建一个空的data.frame。对于向量中的每个数字,您希望将其粘贴到网址中,然后将mutate年份粘贴到df。然后将bind_rows绑定到df。最后,返回football_df,这是所有组合的bind_rows版本。

library(dplyr)

football <- function(numbers){
  football_df <- data.frame()

  for (i in seq_along(numbers)){
    df <- read.csv(paste("http://www.football-data.co.uk/mmz4281/",numbers[i],"/F1.csv", sep=""), stringsAsFactors = FALSE) %>%
      mutate(year = numbers[i])
    football_df <- bind_rows(football_df, df)
  }
  return(football_df)

}


years <- c(1617, 1415, 1314)

final_df <- football(years)