Tdebeus
Tdebeus

Reputation: 1599

My first function in R reading csv's

I've learned that if you are to repeat the same thing over and over again it's wise to write a function. Untill now I've come a long way without writing one myself. The R ecosystem of packages and its functions has treated me well so far.

I'm trying to do the following. Where the q1_2018_raw variable will be replaced with multiple quarters of years 2010 till 2018 so q1_2010_raw till q1_2018_raw. The only thing that will change is the file within read_csv() and the value within add_column(). The rest stays the same.

Then I want to bind all the dataframes together with rbind().

library(tidyverse)

q1_2018_raw <- read_csv("geluidshinder/bas_meldingen_csv/tabula-bijlage_q1-2018.csv",
                        col_names = c("cluster", "woonplaats", 
                                      "sm_nov", "sm_dec", "sm_jan",
                                      "pm_nov", "pm_dec", "pm_jan",
                                      "am_nov", "am_dec", "am_jan",
                                      "totaal", "snachts", "melders")) %>%
  add_column(kwartaal = "q1_2018", .before = T)

Upvotes: 0

Views: 67

Answers (1)

DCZ
DCZ

Reputation: 1744

This should work, if I understood your question correctly.

With csvbeing the variable that will hold your csv, path being the path where your csv is located, and column.name the value in add_column.

customcsvreader <- function(csv, path, column.name){
  csv <- read_csv(path,
                  col_names = c("cluster", "woonplaats", 
                                "sm_nov", "sm_dec", "sm_jan",
                                "pm_nov", "pm_dec", "pm_jan",
                                "am_nov", "am_dec", "am_jan",
                                "totaal", "snachts", "melders")) %>%
  add_column(kwartaal= column.name, .before=T))
}

example:

customcsvreader(q1_2018_raw, "geluidshinder/bas_meldingen_csv/tabula-bijlage_q1-2018.csv", "q1_2018")

Upvotes: 1

Related Questions