简体   繁体   中英

Loop through dataframe and execute SQL query

I have a dataframe which has 6 rows with SQL queries in each line. I want to execute every query and assign the output to a dataframe. currently I have 6 line of codes as below:

df6 <- tbl(conn,sql(df[6,])) Is there a way I can loop through and assign the same in one statement using dplyr mutate function? I tried below:

i <- 1:nrow(df)
df %>% mutate(paste0('df',i) <- tbl(conn,sql(df[i,])))

This throws the following error:

Error: Column q1 must be a 1d atomic vector or a list.

Any help is appreciated.

Your question seems a little unclear, but assuming you have a dataframe with a column titled 'sql_code', you can just apply a function to each element in that column

lapply(df$sql_code, function(x) tbl(conn, sql(x)))

you will end up with a list that you can put together with bind_cols() (if the data frames are of the same dimensions)

With the help from Shinobi_Atobe's function I could develop it into what I wanted as below:

list2env(setNames(lapply(df$sql_query,function(x) {tbl(conn, sql(x))}), paste0('df', 1:nrow(df))), envir=.GlobalEnv)

This executes sql query from every row in the dataframe and stores the output in individual dataframes named as df1,df2...

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM