Printing a database as text

Viewed 53

I'm an R Markdown newbie. I've got a db as follows:

text <- c("aaa","bbb", "ccc")
year <- c(2003,2004,2005)
author <- c("MV", "RV", "MV")
db <- as.data.frame(cbind(text, year, author))

I would like to print it a bullet point as follows:

  • aaa

    2003, MV

  • bbb

    2004, RV

  • ccc

    2005, MV

I tried as follows:

- `r db[1, 1]`

- `r db[1, 2]`
- `r db[1, 3]`

- `r db[2, 1]`

- `r db[2, 2]`
- `r db[2, 3]`

- `r db[3, 1]`

- `r db[3, 2]`
- `r db[3, 3]`

Is there a way to do it automatically without listing each line?

2 Answers

You can write R code that prints your data as markdown text, for example using glue:

library(glue)

text <- c("aaa","bbb", "ccc")
year <- c(2003,2004,2005)
author <- c("MV", "RV", "MV")
db <- as.data.frame(cbind(text, year, author))

glue_data(
  db,
  "* {text}  ",
  "{year} {author}",
  .sep = "\n"
)
#> * aaa  
#> 2003 MV
#> * bbb  
#> 2004 RV
#> * ccc  
#> 2005 MV

If you put this in an RMarkdown chunk with the option results='asis', the generated markdown will be included in your knitted document.

While Joe Roe's answer is perfectly fine, below a solution for people like me who don't like to install packages ;)

In a chunck before the list:

```{r echo=FALSE}
manually_assembled_list <- paste0(
  paste0("* ",   db$text, "  \n"),
  paste0(db$year,  ", ", db$author, "  \n"),
  collapse=""
)
```

And then in the Rmd body:

`r manually_assembled_list`
Related