带有图像的多个 Kable 表 [英] Multiple Kable Tables with Images
问题描述
我正在尝试使用 kable
从 csv 文件创建多个表,但要求是我还需要按照下图将图像放入表中.整个图像需要在左列中.这可能吗?
I'm trying to create multiple tables using kable
from a csv file, but the requirement is that I need to also put an image in the table as per the below image. The entire image needs to be in the left column. Is this possible?
数据框如下所示:
df<-data.frame(Amount= c('$25', '$45', '$75'),
Rate = c('1%', '1%', '3%'),
Location = c('Germany', 'Switzerland', 'England'),
ImageName= c('GE.png', 'BE.png', 'CE.png'),
Status = c('Sold','Unsold','Sold')
)
到目前为止我的 R 代码是
So far my R code is
---
output:
word_document:
reference_docx: ReferenceDoc.docx
---
```{r setup, include=FALSE}
knitr::opts_chunk$set(echo = TRUE)
df<-read.csv('Productdata.csv')
```
```{r loops, echo=F, results='asis'}
library(knitr)
for (i in 1:nrow(df))
{
print(kable(df[i,]))
}
```
我真的不知道如何在我的 RMarkdown for WORD 中输入这样的图像.
Im really not sure how I can enter an image like that in my RMarkdown for WORD.
推荐答案
这是一种使用 kable
和 kableExtra
函数来处理一些格式设置的方法.到目前为止,我只能将其正确呈现为 html.如果我可以在 Word 中完成这项工作,我会更新.在下面的代码中,我使用了一些我碰巧躺在身边的图像.只需在原始 ImageName
列上运行相同的 sprintf
函数,即可为您的图像获取适当的 rmarkdown
标记.
Here's an approach using kable
, along with kableExtra
functions to take care of some of the formatting. So far, I've only been able to render this properly to html. I'll update if I can make this work in Word. In the code below, I used some images I happened to have lying around. Just run the same sprintf
function on your original ImageName
column to get the appropriate rmarkdown
tagging for your images.
---
output:
html_document:
df_print: paged
---
```{r setup, include=FALSE}
knitr::opts_chunk$set(echo = TRUE, warning=FALSE, message=FALSE)
library(knitr)
library(kableExtra)
library(tidyverse)
#df<-read.csv('Productdata.csv')
df<-data.frame(Amount= c('$25', '$45', '$75'),
Rate = c('1%', '1%', '3%'),
Location = c('Germany', 'Switzerland', 'England'),
ImageName= c('GE.png', 'BE.png', 'CE.png'),
Status = c('Sold','Unsold','Sold')
)
# Change to names of my local images
df$ImageName =c("mal2.jpg",
"serenity2.jpg",
"blue_sun2.jpg")
# Add appropriate rmarkdown tagging
df$ImageName = sprintf("![](%s)", df$ImageName)
```
```{r loops, echo=F, results="asis"}
for (i in 1:nrow(df)) {
# Select desired row
d = df[i, ]
# Change name of ImageName column to Status value
names(d)[grep("ImageName", names(d))] = as.character(d[["Status"]])
# Convert data to "long" format
d = d %>%
select(-Status) %>%
gather(Product, value, Amount:Location) %>%
rename(` ` = value)
# Render table using kableExtra for formatting
print(kable(d, format="html") %>%
kable_styling(full_width=FALSE) %>%
collapse_rows(columns=1, valign="top"))
}
```
这里是 html 输出文件的样子:
And here's what the html output file looks like:
这篇关于带有图像的多个 Kable 表的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!