1

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?

Me Myself
  • 105
  • 6

2 Answers2

1

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.

Roman Luštrik
  • 69,533
  • 24
  • 154
  • 197
0

It is not clear how the OP did the coding


title: "Testing"
author: "akrun"
date: "April 28, 2017"
output: pdf_document
---

```{r setup, include=FALSE}
knitr::opts_chunk$set(echo = TRUE)
library(dplyr)
library(tibble)
```

```{r code1, eval=TRUE, echo = FALSE}

animals <- data.frame(species = c("dog", "cat", "dog", "cat"), stringsAsFactors=FALSE)
animals1 <- data_frame(species = c("dog", "cat", "dog", "cat"), stringsAsFactors=FALSE)
animals2 <- as_tibble(animals)
```


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

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

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

gives the output

enter image description here

akrun
  • 874,273
  • 37
  • 540
  • 662