I have a list containing character vectors. I would like to create an unordered list in an RMarkdown document. I have tried to accomplish this by looping through the list and pasting the output in an markdown list. In knitr
in print the results 'asis'
. Here is a toy example.
test <- list(x = c('a', 'b', 'c'), y = c('d', 'e'))
I would like to create an unordered list like this:
- x
- a
- b
- c
- y
- d
- e
I have tried to do this using a for loop in conjunction with cat
and paste0
.
cols <- names(test)
for (columns in names(test)) {
cat(paste0("- ", names(test[columns]), '\n', ' ',
"- ", test[[cols[columns]]], '\n'))
}
Which outputs"
- x
-
- y
-
I would appreciate some help to get the desired unordered list I have described above.
Here's a solution where you don't need loops. List is very similar to yaml document, therefore you can convert it to yaml (modify a little bit) and cat
.
test <- list(A = c("a", "b", "c"), B = c("d", "e"), C = 1:5)
cat(gsub("^!omap\n|:", "", yaml::as.yaml(test, omap = TRUE)))
Explanation:
as.yaml
function from yaml
package. gsub
. cat
result.You can also put it in a custom function so you wouldn't flood code:
catList <- function(inputList) {
cat(gsub("^!omap\n|:", "", yaml::as.yaml(inputList, omap = TRUE)))
}
catList(test)
Try this:
---
title: "SO Answer"
author: "duckmayr"
date: "September 14, 2018"
output: html_document
---
```{r unordered_list, echo=FALSE, results='asis'}
test <- list(x = c('a', 'b', 'c'), y = c('d', 'e'))
for (name in names(test)) {
cat("-", name, '\n', paste(' -', test[[name]], '\n'))
}
```
For me, this yields:
The way you were trying it before had two issues:
test[[columns]]
rather than test[[cols[columns]]]
, andpaste
was causing some issues for you:for (columns in names(test)) {
cat(paste0("- ", names(test[columns]), '\n', ' ',
"- ", test[[columns]], '\n'))
}
- x
- a
- x
- b
- x
- c
- y
- d
- y
- e
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With