MattnDo
MattnDo

Reputation: 444

How to replace this code in r by a function?

I have this code that works but I would like to learn how to replace it by a 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)

For the first step I have tried something like this but it obviously failed:

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

dl_l1(1617)

Upvotes: 0

Views: 58

Answers (3)

Manuel Bickel
Manuel Bickel

Reputation: 2206

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)

Upvotes: 2

amrrs
amrrs

Reputation: 6325

You need to use paste to concatenate to build the url. Below code should work.

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

dl_l1(1617)

#final output

l1_1317 <- bind_rows(dl_l1(1617), dl_l1(1516), dl_l1(1415), dl_l1(1314))

Upvotes: 3

Matt W.
Matt W.

Reputation: 3722

I would create a for loop in a function so you can iterate through a vector of numbers:

create function football that takes a number, or a vector of numbers, then create an empty data.frame. for each number in the vector, you want to paste it into the url, and then mutate the year into that df. Then you bind_rows into the df. At the end you return the football_df which is the bind_rows version of all of the ones combined.

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)

Upvotes: 0

Related Questions