How to iterate over "withTags" and "div"

library(htmltools)
trial <- readLines("trial.txt")

trial consists of :
a
b
c
d

for (i in 1 : 10 ){
  bus <- withTags(
    div(id = i,trial[i]))
  print(bus)
}

I would like the output to be :

<div id="1">a</div>
<div id="2">b</div>
<div id="3">c</div>
<div id="4">d</div>

I am gettting error : Error in trial[i] : invalid subscript type 'closure'

One way to do this is to use map2 from purrr

library(htmltools)
library(purrr)

trial <- readLines("trial.txt")

map2(.x = 1:4,
     .y = trial,
     .f = ~withTags(div(id = .x, 
                        .y)))
#[[1]]
#<div id="1">a</div>
#
#[[2]]
#<div id="2">b</div>
#  
#[[3]]
#<div id="3">c</div>
# 
#[[4]]
#<div id="4">d</div>
1 Like

any chance I can get the output without? :

#[[1]] 
#[[2]]
#[[3]]
#[[4]]

...

Sure, you could pipe it forward into tagList() :slight_smile:

map2(.x = 1:4,
     .y = trial,
     .f = ~withTags(div(id = .x, 
                        .y))) %>% 
  tagList() 
#<div id="1">a</div>
#<div id="2">b</div>
#<div id="3">c</div>
#<div id="4">d</div>

1 Like

however when I am passing over to a file such as :

x <- map2(.x = 1:1000,
     .y = trial,
     .f = ~withTags(div(id = .x, 
                        .y))) %>% 
  tagList()

[[]] comes up again ?

[[1]][[992]]

“Forever?” said the little girl. “Till death itself?”

[[1]][[993]]

[[1]][[994]]

She took his arm and with a happy face went with him into the adjoining sitting room.

This topic was automatically closed 7 days after the last reply. New replies are no longer allowed.