1

How to generate HTML code and assign it to a variable in R without saving it in an HTML file? (i.e)

the function must be like

p <- pairs(data)

res <- htmlcodefunction(p)

res

output must be an HTML code not as a file

1 Answers1

0

You can't encode images as HTML directly. When you see an image in HTML, it is usually done via a link to an image file on the server. However, there are ways round this.

If you want the image data stored as characters within an HTML file, you can either use base64 to encode a raster image, or in the case of vector graphics (like R plots), you can encode as SVG, which is probably what you mean by storing the image as HTML.

Please note that in your example code, you are not actually storing anything to p, because although pairs will draw a plot, it doesn't return an object, so there is nothing there for a function to do anything with.

Anyway, here is a little function that will take a plotting function as an argument and return an svg string, which can be used within HTML:

as_svg <- function(my_plot, ...)
{
  my_plot <- as.call(substitute(my_plot))
  loc <- tempfile()
  svg(loc, ...)
  eval(my_plot)
  dev.off()
  readChar(loc, 1e6L)
}

You can use it like this:

as_svg(plot(rnorm(10), rnorm(10)))
#> [1] "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n<svg xmlns=\"http://www.w3.org/2000/svg\" 
#> xmlns:xlink=\"http://www.w3.org/1999/xlink\" width=\"504pt\" height=\"504pt\" viewBox=\"0 
#> 0 504 504\" version=\"1.1\">\n<defs>\n<g>\n<symbol overflow=\"visible\" id=\"glyph0-0\">
#> \n<path style=\"stroke:none;\" d=\"M 1.5 0 L 1.5 -7.5 L 7.5 -7.5 L 7.5 0 Z M 1.6875 -0.1875 L 
#> 7.3125 -0.1875 L 7.3125 -7.3125 L 1.6875 -7.3125 Z M 1.6875 -0.1875 \"/>\n</symbol>\n<symbol 
#> overflow=\"visible\" id=\"glyph0-1\">\n<path style=\"stroke:none;\" d=\"M 0.382813 -2.578125 L 
#> 0.382813 -3.640625 L 3.621094 -3.640625 L 3.621094 -2.578125 Z M 0.382813 -2.578125 \"/>\n
#> </symbol>\n<symbol overflow=\"visible\" id=\"glyph0-2\">\n<path style=\"stroke:none;\" 
#> d=\"M 6.039063 -1.015625 L 6.039063 0 L 0.363281 0 C 0.355469 -0.253906 0.394531 -0.496094
#> 0.484375 -0.734375 C 0.628906 -1.117188 0.859375 -1.5 1.179688 -1.875 C 1.492188 -2.25 
#> 1.953125 -2.683594 2.5625 -3.175781 C 3.492188 -3.941406 4.125 -4.546875 4.453125 -4.992188 C
#>  ... <truncated>

Allan Cameron
  • 147,086
  • 7
  • 49
  • 87