Rohan Kataria
Rohan Kataria

Reputation: 89

What is a loop solution for the given code in R?

I want combined data for the last 7 days. I'm using the following code to get my result, but that is not the appropriate way. Using for loop gives me an error. Maybe I'm doing it wrong.

tables <- db_list_tables(con)
tables
#Total 366 days

day_366 <- tbl(con, "ga_sessions_20170801") %>%
  head(10) %>% 
  collect()

day_365 <- tbl(con, "ga_sessions_20170730") %>%
  head(10) %>% 
  collect()

day_364 <- tbl(con, "ga_sessions_20170729") %>%
  head(10) %>% 
  collect()

day_363 <- tbl(con, "ga_sessions_20170728") %>%
  head(10) %>% 
  collect()

day_362 <- tbl(con, "ga_sessions_20170727") %>%
  head(10) %>% 
  collect()

day_361 <- tbl(con, "ga_sessions_20170726") %>%
  head(10) %>% 
  collect()

day_360 <- tbl(con, "ga_sessions_20170725") %>%
  head(10) %>% 
  collect()

day_359 <- tbl(con, "ga_sessions_20170724") %>%
  head(10) %>% 
  collect()

seven_days <- rbind(day_366, day_365, day_364, day_363, day_362, day_361, day_360, day_359)

Upvotes: 1

Views: 66

Answers (1)

akrun
akrun

Reputation: 887891

We can loop over the objects and collect

library(purrr)
library(dbplyr)  
ga_session <- sprintf("ga_sessions_%d", c(20170801, 20170730:20170724))   
seven_days <- map_dfr(ga_session,  ~  tbl(con, .x) %>%
             head %>%
             collect())

Or using a for loop

lst1 <- vector('list', length(ga_session)
for(i in seq_along(ga_session)) {
    lst1[[i]] <- tbl(con, ga_session[i]) %>% 
                 head %>%
                 collect()
   }
out <- do.call(rbind, lst1) 

Upvotes: 1

Related Questions