Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
533 views
in Technique[技术] by (71.8m points)

dataframe - Add an image to a table-like output in R

I have a simple data structure: cases are countries and for each country I have a couple of numeric variables. Like so:

dat <- data.frame(country = c("Belgium", "Germany", "Holland", "Ireland"), Var1 = 1:4, Var2 = 11:14)
print(dat, row.names = FALSE)

 country Var1 Var2
 Belgium    1   11
 Germany    2   12
 Holland    3   13
 Ireland    4   14

The table needs to be formatted still, with headings in bold, and rows colored in grey or white, alternatingly.

Now, what I want is to add two additional columns, in between "country" and "Var1". The first new column is called "flag" and should contain the country's flag. The second new column is called "flagged" and contains an image of a red flag is the country scores very bad on a particular human rights issue, an orange flag if it scores mediocre and nothing elsewise.

How can I create an object that prints that way in R? How to combine images with data in such a layout?

(eventually this will part of a larger document created with knitr)

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

If you are using knitr with the rmarkdown package, it is pretty easy -- just use the Markdown syntax ![]() to include images, e.g.

---
title: "Flags"
author: "Yihui Xie"
date: "2014/08/03"
output: html_document
---

```{r results='asis'}
dat <- data.frame(
  country = c('Canada', 'United Kindom'),
  abbr = c('ca', 'gb'),
  var1 = c(1, 2),
  var2 = rnorm(2)
)
dat$flag <- sprintf('![](http://flagpedia.net/data/flags/mini/%s.png)', dat$abbr)
library(knitr)
kable(dat)
```

knitr, tables, and flags

If you need LaTeX/PDF output, you have to download these images by yourself. Here is an example:

---
title: "Flags"
author: "Yihui Xie"
date: "2014/08/03"
output: html_document
---

```{r}
dat <- data.frame(
  country = c('Canada', 'United Kindom'),
  abbr = c('ca', 'gb'),
  var1 = c(1, 2),
  var2 = rnorm(2)
)
dat$file <- paste0(dat$abbr, '.png')
dat$link <- paste0('http://flagpedia.net/data/flags/mini/', dat$file)
dat$flag <- sprintf('![](%s)', dat$file)
for (i in seq_len(nrow(dat))) {
  if (!file.exists(dat$file[i])) xfun::download_file(dat$link[i])
}
knitr::kable(dat[, -c(5, 6)])
```

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...