extracting field names and groupings from an unevaluated lazy tibble

I have a situation where I have an unevaluated lazy tibble against a database. Not unlike mtcars2 in the example below:

library(tidyverse)
con <- DBI::dbConnect(RSQLite::SQLite(), ":memory:")
copy_to(con, mtcars)

mtcars2 <- tbl(con, "mtcars") %>%
  select(mpg, cyl, gear, hp) %>%
  group_by(cyl) 

I'd like to test and make sure that a specific column exists in the data frame. I'd also like to check the groupings. How can I do that on a lazy tibble? Since it's unevaluated, names just returns the list names:

names(mtcars2)
#> [1] "src" "ops"

The field names are, of course, in the tibble structure. But I can't see any easy way to pop them out:

mtcars2$ops$x$dots
#> [[1]]
#> <quosure>
#> expr: ^mpg
#> env:  0x7fbb5a3bb518
#> 
#> [[2]]
#> <quosure>
#> expr: ^cyl
#> env:  0x7fbb5a3bb518
#> 
#> [[3]]
#> <quosure>
#> expr: ^gear
#> env:  0x7fbb5a3bb518
#> 
#> [[4]]
#> <quosure>
#> expr: ^hp
#> env:  0x7fbb5a3bb518
1 Like

If I remember correctly colnames() works for remote tibbles (while names() does not - don't ask me why...)

3 Likes

Yep, colnames totally works. Thank you! Any ideas how to extract the group_by fields?

Sorry, don't know this one.

turns out it's group_vars to get the groupings:

colnames(mtcars2)
#> [1] "mpg"  "cyl"  "gear" "hp"

group_vars(mtcars2)
#> [1] "cyl"
3 Likes

Thanks, I will keep that in mind.

It is interesting that group_vars() behaves for remote tibbles differently from plain o'l vars()

library(tidyverse)
con <- DBI::dbConnect(RSQLite::SQLite(), ":memory:")
copy_to(con, mtcars)

mtcars2 <- tbl(con, "mtcars") %>%
  select(mpg, cyl, gear, hp) %>%
  group_by(cyl)

group_vars(mtcars2)
#> [1] "cyl"
vars(mtcars2)
#> [[1]]
#> <quosure>
#> expr: ^mtcars2
#> env:  global
colnames(mtcars2)
#> [1] "mpg"  "cyl"  "gear" "hp"

I dunno....

This topic was automatically closed 7 days after the last reply. New replies are no longer allowed.

If you have a query related to it or one of the replies, start a new topic and refer back with a link.