While Loop W/ Nested If Else

Hi @kwgood1980! Something we find quite often on these forums (for example, in this thread) is people trying to approach a problem in R as they would in another language. I've certainly done it a lot!

My read on your post is that you have a bunch of CSV files, and you want to send each one to a database (sorry to sound like a call centre employee; I just wanna make sure I have it right).

If you'd prefer to stick with loops, you can actually iterate directly over the values of a vector in R, or you can generate a vector of indices in another vector with seq_along. This is a lot less prone to bugs. For example:

myfiles = c('apple.csv', 'banana.csv', 'pineapple.csv')

for (i in seq_along(myfiles)) {
  # note: check the case in stringsAsFactors!
  df <- fread(myfiles[i], stringsAsFactors = FALSE)
  sqlSave(con, df, tablename = paste0('dbo.file', i), colnames = FALSE, rownames = FALSE, append = TRUE)
}

Another solution using the purrr package would be to have a data frame with columns (vectors) for CSV file names and associated database table names, and to then apply a function over these two columns element-by-element. The function would load each CSV in and save to the database table:

library(tidyverse)
library(purrr)
myfiles = data_frame(
  csv = c('apple.csv', 'banana.csv', 'pineapple.csv'),
  table = c('dbo.apple', 'dbo.banana', 'dbo.pineapple'))

# map2 calls a function for each pair of elements fro mtwo vectors
map2(myfiles$csv, myfiles$table, function(csv_i, table_i) {
  # in this function, csv_i is an element of myfiles$csv and
  # table_i is an element of myfiles$table
  df <- fread(csv_i, stringsAsFactors = FALSE)
  sqlSave(con, df, tablename = table_i, colnames = FALSE, rownames = FALSE, append = TRUE)
})

If you're interested in how purrr functions like map2 work, check out this chapter of Advanced R! it's a very powerful way of working! I hope one of these approaches works for you :slight_smile:

5 Likes