export table from R with ReporteRs with cells colored according to value

99 Views Asked by At

Using the ReporteRs package in R I would like to export a data frame with colored cells to a table in a word document.

Following the code and instructions provided on this website: http://www.sthda.com/english/wiki/add-a-table-into-a-word-document-using-r-software-and-reporters-package

I tried to add colors to the cells in the table I am preparing. But I am unable to get the correct colors in the cells in the table I export.

The code below has a test data frame, and also installs the package. The code produces a word.doc file with a table in, but the colors in the cells are wrong. The colors in the cells in the table in the word document are not matching the values that are in the cells. I suspect I have set the 'breaks' incorrect, but I am not sure how to set them correctly to get the table I want.

My input data frame has values from 1 to 5, and I would like the cells to be colored according to their values. i.e. a cell with value 1 should be purple, a cell with value 2 should be blue, a cell with value 3 should be darkgreen, a cell with value 4 should be green and a cell with value 5 should be yellow.

#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")
0

There are 0 best solutions below