Home > Net >  Selecting rows in package `gt` using expressions
Selecting rows in package `gt` using expressions

Time:10-20

The reference for fmt_number() says that one may select rows using an expression:

rows

Optional rows to format. Providing either everything() (the default) or TRUE results in all rows in columns being formatted. Can either be a vector of row captions provided in c(), a vector of row indices, or a helper function focused on selections. The select helper functions are: starts_with(), ends_with(), contains(), matches(), one_of(), num_range(), and everything(). We can also use expressions to filter down to the rows we need (e.g., [colname_1] > 100 & [colname_2] < 50).

However, I haven't find out how to make this work. I tried the following (this is just an illustration; these number transformations do not make sense in this data set):

library(gt)
library(tidyverse)

df = starwars

gt_tb = gt(df) %>%
    fmt_number(
        rows = [birth_year] > 20,
        pattern = '({x})'
    )

gt_tb = gt(df) %>%
  fmt_number(
    columns = mass,
    rows = [birth_year] > 20,
    pattern = '({x})'
  )

gt_tb = gt(df) %>%
  fmt_number(
    columns = mass,
    rows = expression([birth_year] > 20),
    pattern = '({x})'
  )

gt_tb = gt(df) %>%
  fmt_number(
    columns = mass,
    rows = df[birth_year] > 20,
    pattern = '({x})'
  )

gt_tb = gt(df) %>%
  fmt_number(
    columns = mass,
    rows = everything([birth_year] > 20),
    pattern = '({x})'
  )

Also tried their quoted equivalent.

Pretty new to this package, sorry if I missed something evident!

CodePudding user response:

You also have to specify columns:

df %>%
  gt() %>% 
  fmt_number(
    columns = where(is.numeric),
    rows = birth_year > 20,
    pattern = '({x})'
  )

This gives us (as a screenshot/sample):

CodePudding user response:

We can also use expressions to filter down to the rows we need (e.g., [colname_1] > 100 & [colname_2] < 50).

The example uses the brackets ([]) to tell you that those are placeholders, it's not a valid syntax.

In your case it would be

    fmt_number(
        columns = mass,
        rows = birth_year > 20,
        pattern = '({x})'
    )
  •  Tags:  
  • r gt
  • Related