Snippets

Little bits of code.

This is a place where I will put little bits of useful code with examples…for you to learn from, and for me to remember!

Unfortunately, I have lost the references to most of them, so to those of you out there who figured these out first, thanks & sorry!

Pipelining a wildcard in a filter

2022-12-25

So here is the scenario. I have a data frame like so:

df <- tribble(
  ~doc, ~val,
  'B',1,
  'B',2,
  'BC',1,
  'BC',4,
  'D',5
)

df
# A tibble: 5 × 2
  doc     val
  <chr> <dbl>
1 B         1
2 B         2
3 BC        1
4 BC        4
5 D         5

and I want to do a filter in a long sequence of code. But I want to be able to find all rows if the user enters ‘ALL’, or just the matching rows if they enter something else. So ‘ALL’ acts like a wildcard.

For example, if the user enters (say into a variable docname) B, I want the pipeline to return the first two rows. But if they enter ALL, I want all rows returned.

Here is how to do it.

docname<-'B'
df %>% {if(docname!='ALL') filter(., doc == docname) else .} 
# A tibble: 2 × 2
  doc     val
  <chr> <dbl>
1 B         1
2 B         2
docname<-'BC'
df %>% {if(docname!='ALL') filter(., doc == docname) else .} 
# A tibble: 2 × 2
  doc     val
  <chr> <dbl>
1 BC        1
2 BC        4
docname<-'ALL'
df %>% {if(docname!='ALL') filter(., doc == docname) else .} 
# A tibble: 5 × 2
  doc     val
  <chr> <dbl>
1 B         1
2 B         2
3 BC        1
4 BC        4
5 D         5

Further discussions with Chris have lead me to conclude that the best way to do this is to use anonymous functions like the following, rather than the curly bracket trick:

df |> (\(.) if(docname!='ALL') filter(., doc == docname) else .)()
# A tibble: 5 × 2
  doc     val
  <chr> <dbl>
1 B         1
2 B         2
3 BC        1
4 BC        4
5 D         5

This way composes well with other steps in a pipeline and does not require using helper functions that litter the code. And it works with both %>% and |>.

Labelling in latex

2022-12-25

When writing a mathy document, it can be helpful to explain what each part of an equation means. underbrace and text are your friends.

Here is an example

\[y=\underbrace{3 \alpha}_\text{What alpha means}\times \underbrace{f\left( x^3\right)}_\text{why x cubed?}\] The latex is:

y=\underbrace{3 \alpha}_\text{What alpha means}\times \underbrace{f\left( x^3\right)}_\text{why x cubed?}

For a slightly better looking version with just a bit more complication:

\[ y = \underbrace{3 \alpha}_{\text{What } \alpha \text{ means}} \times \underbrace{f\left( x^3\right)}_{\text{why } x^3 \text{?}} \]

The latex here is:

y = \underbrace{3 \alpha}_{\text{What } \alpha \text{ means}} \times \underbrace{f\left( x^3\right)}_{\text{why } x^3 \text{?}}