我有一个关于在R笔记本中输出内联数字的问题。 我想使用dplyr和管道切换到更易读的代码,但现在我想要计算的数字不再与文本一致。
到目前为止,我编写了这样的代码:
Number of dogs: `r nrow(animals[which(animals$species == "dog"),])`!
我得到了数字内联:
Number of dogs: 8!
如果我切换到
Number of dogs: `r animals %>% filter(species == "dog") %>% count()`!
输出不再是内联的,而是插入到下面的行中,周围有一个框:
Number of dogs:
[ n]
[ <int>]
[ 90]
[1 row ]
!
如何获取内联输出?
答案 0 :(得分:1)
结果被强制转换为tibble
。
library(dplyr)
(xy <- iris %>% filter(Species == "setosa") %>% count())
# A tibble: 1 × 1
n
<int>
1 50
将其包裹到as.numeric
以获得单个数字(长度为1的向量)。
> as.numeric(xy)
[1] 50
unlist(xy)
也有效。
答案 1 :(得分:0)
目前尚不清楚OP如何编码
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()`!
给出输出