Search code examples
rr-markdownreportinline

R markdown: report values from dataframe as text


Using modified mtcars dataset I try to get this output after knitting a Rmd file to html:

"The database consists of 5 car models (Mazda RX4 (mpg=21.0), Mazda RX4 Wag (mpg=21.0), Datsun 710 (mpg=22.8), Hornet 4 Drive (mpg=21.4), and Hornet Sportabout (mpg=18.7)."

What I achieved so far:

"The database consists of 5 car models (Mazda RX4, Mazda RX4 Wag, Datsun 710, Hornet 4 Drive, and Hornet Sportabout)."

Is there a way to put each mpg of the dataframe to the model of car inline? Thank you!

my Rmd file:

YAML

---
title: "test"
author: "TJ"
date: "27 12 2020"
output: html_document
---

chunk1

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

chunk 2

{r cars}
df <- mtcars %>% 
  mutate(car=rownames(mtcars),
         id = row_number()
         ) %>% 
  filter(id <= 5) %>% 
  select(car, mpg)

# count of cars
n_cars <- length(df)

# mpg of cars
mpg_cars <- df$car %>% 
  glue_collapse(sep = ", ", last = ", and ")

inline

The database consists of `r nrow(df)` car models (`r mpg_cars`).

Solution

  • Sorry for deleting so many times , i was working to get the best code Here is the code

    datasets::mtcars
    cars<-mtcars
    cars$make<- row.names(cars)
    cars$mpg_1<-as.character(cars$mpg)
    cars$x=paste(cars$make,cars$mpg_1,sep = ",")
    View(cars)
    

    enter image description here