Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Convert list object to unordered list in markdown

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.

like image 219
babylinguist Avatar asked Sep 14 '18 15:09

babylinguist


2 Answers

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:

  • convert list to ordered yaml using as.yaml function from yaml package.
  • Remove omap header using gsub.
  • cat result.

enter image description here


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)
like image 65
pogibas Avatar answered Oct 16 '22 22:10

pogibas


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:

enter image description here

The way you were trying it before had two issues:

  1. You should have been subsetting by test[[columns]] rather than test[[cols[columns]]], and
  2. Even after you fix that, you can see that paste 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
like image 27
duckmayr Avatar answered Oct 16 '22 21:10

duckmayr