2

I have a vector with table names:

table_names <- c("table1", "table2", "table3", "table4")

I want to query all this tables with limit 100 using for loop like this:

for (val in table_names){
   my_query = pastge0("SELECT * FROM", val, " LIMIT 100")
   dbGetQuery(con, my_query)

As you see this looping creates 4 querys and 4 tables. However I want those tables to be named. How to get these for tables?

french_fries
  • 1,149
  • 6
  • 22

1 Answers1

3

It's often best to use lapply and keep the frames in a list (see https://stackoverflow.com/a/24376207/3358227):

allfour <- lapply(setNames(paste("select * from", table_names, "limit 100"),
                           table_names),
                  DBI::dbGetQuery, conn = con)

If you don't want them in a list, then you can assign them to an environment with list2env, such as

list2env(allfour, envir = .GlobalEnv)
r2evans
  • 141,215
  • 6
  • 77
  • 149
  • thanks, but i need four tables in my Environment in R, not nested list – french_fries Jul 07 '21 at 19:53
  • is it possible to give those tables according names from table_names? – french_fries Jul 07 '21 at 19:59
  • 1
    @french_fries Think twice before looking at r2evans' edit. Usually keeping things in a list is the better choice: You avoid cluttering your namespace, you can easily access every table within the list and you keep all of the `lapply`-etc goodness. – Bernhard Jul 07 '21 at 20:17