rgoogle-bigquerytidyversedbplyrbigrquery

Week of year using bigquery / bigrquery and dbplyr? (equivalent of lubridate::week)


I'm trying to use bigrquery and dbplyr to get the week of the year that a date corresponds to (i.e. the same as lubridate::week(), i.e.

library(lubridate)
library(dbplyr)
library(bigrquery)

week("2015-08-11")   
# [1] 32

but I am using bigrquery and dbplyr

What I've tried so far

Using lubridate::week() I see

transactions %>% 
  select(item, date) %>% 
  mutate(week = week(date)) %>%
  collect()
Error: Function not found: week at [1:30] [invalidQuery]

So I attempted this home made solution

transactions %>% 
  select(item, date) %>%
  mutate(week = strftime(date, format = "%V")) %>% 
  collect()

Error: Syntax error: Expected ")" but got keyword AS at [1:54] [invalidQuery]
In addition: Warning message:
  Named arguments ignored for SQL strftime 

as well as another (fairly ugly) home made solution

transactions %>% 
  select(item, date) %>% 
  mutate(week = as.numeric((as.Date(date) - as.Date(paste0(substr(date, 1, 4), "-01-01"))), units="days") %/% 7) %>% 
  collect()

Error in as.numeric((as.Date(date) - as.Date(paste0(substr(date, 1,  : 
unused argument (units = "days")

but I cannot seem to find a way to get the week number using bigquery and dbplyr


Solution

  • I cannot seem to find a way to get the week number using bigquery

    Looks like you are looking for below BigQuery Standard SQL function

    EXTRACT(WEEK FROM date)    
    

    You can use WEEK or WEEK(< WEEKDAY>) or ISOWEEK

    See more about date part here https://cloud.google.com/bigquery/docs/reference/standard-sql/date_functions#extract