rr-markdown

Concatenate cells into a text list for output in R


I have a table of academic courses and professional competencies such that each course is marked as meeting specific competencies. E.g.:

CourseNumber CourseName Competency 1 Competency 2
101 Intro X
201 Intermediate X
301 Advanced X X

Working in R Markdown, I'd like to be able to pull lists of all courses that meet a given competency. The output I'd like to see, for starters, is:

[pull a list for Competency 1]
101 Intro
301 Advanced

So far, here is the code I've figured out:

compcourses <- function (competency){
                  courselist <- sprintf("%s %s",Table$CourseNumber[which(!is.na(Table[[competency]]))],Table$CourseName[which(!is.na(Table[[competency]]))])
                  return(courselist)
                }

However, in the R Markdown document:

`r compcourses("Competency 1")'

results in the following output:

101 Intro, 301 Advanced

I can't figure out where the damn comma is coming from, how to suppress it, or how to get output such that each course is on its own separate line.

Any assistance greatly appreciated.


Solution

  • The issue is that you are using an inline code chunk with a function which returns a vector of length > 1. Instead you can use a code chunk with results="asis" and use cat as already suggested by @TimG in the comments. However, for your use case I would also suggest to have a look at the epoxy package which allows for easy reporting using some sort of super-glue, e.g. using epoxy you can easily create a list of your data frame rows and style using markdown:

    ---
    output: html_document
    ---
    
    ```{r setup, include=FALSE}
    library(epoxy)
    ```
    
    ```{r}
    Table <- data.frame(
      stringsAsFactors = FALSE,
      CourseNumber = c(101L, 201L, 301L),
      CourseName = c("Intro", "Intermediate", "Advanced"),
      "Competency 1" = c("X", NA, "X"),
      "Competency 2" = c(NA, "X", "X"),
      check.names = FALSE
    )
    ```
    
    ```{r}
    compcourses <- function(competency) {
      dat <- Table[!is.na(Table[[competency]]), ]
      sprintf("%s %s", dat$CourseNumber, dat$CourseName)
    }
    ```
    
    As the output of `compcourses` is a vector, possibly of length > 1 you can use a
    code chunk (with `results='asis'`) instead of an inline chunk:
    
    ```{r results='asis'}
    cat(compcourses("Competency 1"), sep = "\n\n")
    ```
    
    Also you might have a look at the `epoxy` package:
    
    ```{epoxy .data = subset(Table, !is.na(`Competency 1`))}
    - **{CourseNumber}** {CourseName}
    ```
    

    enter image description here