Reputation: 182
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.
Upvotes: 0
Views: 725
Reputation: 182
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...
Upvotes: 0
Reputation: 1963
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)
Upvotes: 1