Search code examples
rr-markdownquarto

How to convert integers to English words in markdown inline code


I'm writing a document using Quarto Markdown (though the problem persists in R Markdown) where I want to include a small variable number in my commentary as a written word and not an integer. From this question I found that the best approach to this problem is using as.english() from the english package (none of the other solutions posed in this question worked for me).

However, this function isn't working properly when used as inline code. For example, the sentence

There are `r as.english(2)` duplicate rows in the dataset.

is rendering as the following in my markdown file:

There are 2 duplicate rows in the dataset.

But I want it to say:

There are two duplicate rows in the dataset.

I tried surrounding the inline code in brackets as suggested in this question, but the result is the same. It's also worth noting that the function is working as expected when run inside an R chunk:

```{r}
library(english)
as.english(2)
```
[1] two

Any ideas why this is happening? I'm certainly open to other approaches if it just comes down to a bug in this package.


Solution

  • We have to wrap it in as.character() or paste0():

    `r as.character(english::as.english(2))`
    
    
    `r paste0(english::as.english(2))`
    

    Then it will work.

    I think the reason is, two is only the print output, and the function returns invisibly 2 so that we can compute on it:

    english::as.english(2) + 1
    #> [1] three
    

    But when turned to a character vector it takes the intended value.

    paste(english::as.english(2)) + 1
    #> Error in paste(english::as.english(2)) + 1: non-numeric argument to binary operator
    
    paste(english::as.english(2), " + 1")
    #> [1] "two  + 1"
    

    It also states in the documentation under Value:

    A numerical object that can be printed as English words, or coerced to character as English words

    Created on 2023-02-21 with reprex v2.0.2