Bruno Guarita
Bruno Guarita

Reputation: 817

Generate html code using lapply() with multiple arguments

I am trying to generate several html paragraphs in a loop using lapply(). These paragraphs are in a data.frame and the data.frame have more columns with details for the paragraphs (class, id, etc). I was able to produce the loop with only one argument, the problem is that I want more than one argument in the lapply() loop. Does anyone knows how to do this?

The data.frame:

df = data.frame(paragraph = c("paragraph1","paragraph2","paragraph3"),
                class= c("alert", "good", "alert"),
                id= c("id_1","id_2", "id_3"))

The objective is to have the following output:

<div>     
     <p class="alert" id="id_1">paragraph1</p> 
     <p class="good" id="id_2">paragraph2</p> 
     <p class="alert" id="id_3">paragraph3</p> 
</div>

The lappy() loop (for one argument only):

library(htmltools)
tags$div(lapply(df$paragraph, function(x){tags$p(class="", id="", x)}))

How can I do it so that the class and id gets filled in with the data in column class and id in df?

Upvotes: 0

Views: 142

Answers (1)

Ben
Ben

Reputation: 30474

You can use apply row-wise, and specify class, id, and content from your data frame as follows.

library(htmltools)

tags$div(apply(df, 1, function(x) {
  tags$p(class = x[["class"]], id = x[["id"]], x[["paragraph"]])
}))

Output

<div>
  <p class="alert" id="id_1">paragraph1</p>
  <p class="good" id="id_2">paragraph2</p>
  <p class="alert" id="id_3">paragraph3</p>
</div>

Upvotes: 1

Related Questions