french_fries
french_fries

Reputation: 1

How to query tables with for loop in R?

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?

Upvotes: 2

Views: 217

Answers (1)

r2evans
r2evans

Reputation: 160447

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)

Upvotes: 3

Related Questions