1

在 RI 中使用 ReporteRs 包希望将带有彩色单元格的数据框导出到 Word 文档中的表格中。

按照本网站提供的代码和说明:http: //www.sthda.com/english/wiki/add-a-table-into-a-word-document-using-r-software-and-reporters-package

我试图为我正在准备的表格中的单元格添加颜色。但是我无法在导出的表格中的单元格中获得正确的颜色。

下面的代码有一个测试数据框,也安装了包。该代码生成一个 word.doc 文件,其中包含一个表格,但单元格中的颜色是错误的。Word 文档中表格中单元格的颜色与单元格中的值不匹配。我怀疑我设置的“休息”不正确,但我不确定如何正确设置它们以获得我想要的表格。

我的输入数据框的值从 1 到 5,我希望根据它们的值对单元格进行着色。即值为 1 的单元格应为紫色,值为 2 的单元格应为蓝色,值为 3 的单元格应为深绿色,值为 4 的单元格应为绿色,值为 5 的单元格应为黄色。

#get the packages required
install.packages("ReporteRs")
library(ReporteRs)

# set working directory
setwd ("/your_own_working_dir/")

#make some test data
c2 <- c(1,2,3,5)
c3 <- c(2,2,3,2)
c4 <- c(4,3,2,1)
#bind the data in to a dataframe
cc <- t(cbind(c2,c3,c4))
dd <- as.data.frame(cc)

#turn the dataframe into a matrix
ee <- matrix(as.numeric(unlist(dd)),nrow=nrow(dd))

#define colors
#col =c("#FB0000", "#FB7F00", "#FBF000", "#6EFF4C")
col =c("purple", "blue", "darkgreen", "green", "yellow")

mycut = cut(ee,
            #breaks = c(-1,-0.75,-0.5,-0.25,0,0.25,0.5,0.75,1),
            breaks = c(1, 2, 3, 4 ,5),
            include.lowest = TRUE, label = FALSE )
color_palettes = col[mycut]
#see the colors in the color palette
unique(color_palettes)

corrFT = FlexTable( ee, add.rownames = TRUE )
corrFT = setFlexTableBackgroundColors(corrFT,
                                      j = seq_len(ncol(ee)) + 1,
                                      colors = color_palettes )
#show_col(color_palettes) #install from "scales" package
#make an empty doc
doc <- docx()

corrFT = setFlexTableBorders( corrFT
                              , inner.vertical = borderProperties( style = "dashed", color = "white" )
                              , inner.horizontal = borderProperties( style = "dashed", color = "white"  )
                              , outer.vertical = borderProperties( width = 2, color = "white"  )
                              , outer.horizontal = borderProperties( width = 2, color = "white"  )
)
doc <- addFlexTable( doc, corrFT)
writeDoc(doc, file = "r-reporters-word-document-correlation.docx")
4

0 回答 0