Search code examples
rdplyrknitrrnotebook

Output of numbers in R notebook


I have a question concerning outputting numbers inline in a R notebook. I wanted to switch to a more readable code using dplyr and pipes, but now the numbers I would like to compute are no longer shown in line with the text.

So far, I wrote my code like this:

Number of dogs: `r nrow(animals[which(animals$species == "dog"),])`!

And I got the numbers inline:

Number of dogs: 8!

If I switch to

Number of dogs: `r animals %>% filter(species == "dog") %>% count()`!

The output is no longer inline, but inserted in the line below, with a box around it:

Number of dogs:
[              n]
[          <int>]
[             90]
[1 row          ]
!

How do I get the inline output back?


Solution

  • The result is coerced to a tibble.

    library(dplyr)
    
    (xy <- iris %>% filter(Species == "setosa") %>% count())
    
    # A tibble: 1 × 1
          n
      <int>
    1    50
    

    Wrap it into as.numeric to get a single digit (vector of length 1).

    > as.numeric(xy)
    [1] 50
    

    unlist(xy) also works.