R-markdown: Reading names from the dataframe and print column values to a word document

Viewed 83

I have a .csv file like below. I want to write the id (id1, id2, id3) values in the word document that I am creating in R-markdown. It is easy to filter the row manually each time (filter(Name == "Andrew"))but how do I do it through code so that I do not have to filter manually each time for each name. I want to create a word document for each name.

data.csv:
Name Country id1 id2 id3
Andrew Germany 23 253 81
Tim Peru 28 789 1
JK Spain 45 678 22
Nina Korea 53 67 89

My code:
```{r, warning=FALSE, echo=FALSE, message=FALSE}
library(dplyr)
data<-read.csv("data.csv")
mydata<-data %>% filter(Name == "Andrew")

```

```{r, warning=FALSE, echo=FALSE, message=FALSE, comment='\t'}

cat(sprintf("The employee %s from %s with %s is associated with number %s",mydata$Name, mydata$country, mydata$id1, mydata$id2))


```

And then I just knit the document. How do I create a separate word document for each name (So 4 documents in this case)containing details for that name only?

Thanks in advance

1 Answers

This could be achieved via a parametrized report. To this end you could use a report template which takes the name as a parameter:

---
output: word_document
params:
  name: Andrew
---

```{r, warning=FALSE, echo=FALSE, message=FALSE}
library(dplyr)
data <- read.csv("data.csv")
mydata <- data %>%
  filter(Name == params$name)
```

```{r, warning=FALSE, echo=FALSE, message=FALSE, comment='\t', results='asis'}
cat(sprintf("The employee %s from %s with %s is associated with number %s", mydata$Name, mydata$Country, mydata$id1, mydata$id2))
```

Afterwards you could use render::rmarkdown to loop over a vector of desired names to create a report for each name like so:

names <- c("Andrew", "Tim", "JK", "Nina")

lapply(names, function(x) rmarkdown::render("report-template.Rmd", output_file = paste0("report-for-", x), params = list(name = x)))
Related