1

I am creating a pdf document in R markdown (.Rmd file)- using latex and R. The R data frame consists of mainly two columns- string column 'Ind' and numeric value 'value'. I need to create 2 types of tables using latex from this R dataframe:

Table 1 requires simple listing of chosen rows from the dataframe with colour coding for the column 'value' (so 2 columns, Ind and value).

For colour coding, I created a new column value_color in the R dataframe using /cellcolor and pasted this cell for the column "value" in the output table I created.It works fine.

enter image description here

Table 2 requires listing of some chosen values of 'Ind', value, and then again some more values of 'Ind' and value (so 4 columns, they are called "Actual","Actual-value","Supposed","Supposed-value").

In Table 2, there is multirow required in some rows. In these multirow merged cells, I pasted column value_color in the R dataframe like in table 1. The text from the pasted cell is adjusting into the merged cell, but the colour is still limited to only one row(and not the merged row.)

enter image description here

If someone can help me in pasting a single cell from one table into a merged cell in a new table, that would be very helpful!

Other options I tried:

  1. I had tried to colour code the tables using a macro, but ran into problems with the complexity of the conditions for colouring in the syntax (I have simplified them here- there are 5 conditions for colouring)
  2. I have tried doing multirow in first row so \multirow{2}... as well as in last row \multirow{-2}... The problem is the same- the cell is not pasted into the merged cell.
  3. Tried repeating pasting the coloured cell for all top 3 rows and doing a multirow{-3} in the end for the column 4- text is still appearing twice in the final table
---
documentclass: article
classoption: twocolumn
geometry: "left=0.5cm,right=0.5cm,top=1.5cm,bottom=1.2cm"
header-includes: \usepackage{fancyhdr} \usepackage{booktabs,xcolor} \pagestyle{fancy}
  \renewcommand{\headrulewidth}{0pt} \rhead{2019} \fancypagestyle{plain}{\pagestyle{fancy}}
  \setlength{\headheight}{77.3pt} \setlength{\footskip}{35.1pt} \setlength{\textheight}{0.90\textheight}
  \pagenumbering{gobble} \usepackage[fontsize=9pt]{scrextend} \usepackage{float} \restylefloat{table}
  \usepackage{xcolor} \usepackage{multicol} \usepackage{array} \usepackage{colortbl}
  \usepackage{multirow} \usepackage{collcell} \newcommand{\hideFromPandoc}[1]{#1}
  \hideFromPandoc{ \let\Begin\begin \let\End\end } \usepackage{caption} \captionsetup{skip=0pt}
  \setlength{\columnsep}{1.5cm}
output:
  pdf_document:
    fig_caption: yes
    keep_tex: yes
    latex_engine: pdflatex
---
    #R code chunk with dataframe

    #include packages
    library(tidyverse)
    library(haven)
    library(dplyr, warn.conflicts = FALSE)
    library(tidyr)
    library(stringr)
    library(scales)
    library(readxl)
    library(glue)

    Ind <- c("M.1a",
             "N.1a",
             "P.1a",
             "Sk.0",
             "Sk.1",
             "Sk.2",
             "Tr.f",
             "M.b",
             "TR.1",
             "TR.a")
    value <- c(as.numeric("9"),
               as.numeric("4"),
               as.numeric("7"),
               as.numeric("9"),
               as.numeric("3.5"),
               as.numeric("2.9"),
               as.numeric("8"),
               as.numeric("5"),
               as.numeric("3"),
               as.numeric("3.5"))
    main <- as.data.frame(cbind(Ind,value))
    main <- main %>%
      mutate(value=round(as.numeric(value), digits=1))

    main <- main %>%
      as_tibble(.name_repair = 'universal') %>%
      mutate(value_color=case_when(
        value >=4 ~ paste("\\cellcolor{green}",value, sep=""),
        value >=3 & value<4  ~ paste("\\cellcolor{yellow}",value, sep=""),
        value <3 ~ paste("\\cellcolor{red}",value, sep="")))
    #R code chunk over
    ```

### Table 1. Indicators ###
\begin{table}[H]
\resizebox{\columnwidth}{!}{\begin{tabular}{lc}
\textbf{Indicator}      & \textbf{Value}\\\hline
\multirow{3}{*}{Ind1}   & `r main$value_color[main$Ind =="M.1a"]` \\\cline{2-2}
                        & `r main$value_color[main$Ind =="N.1a"]` \\\cline{2-2}
                        & `r main$value_color[main$Ind =="P.1a"]` \\\hline
\end{tabular}}
\end{table}

### Table 2. Indicators-Actual vs. supposed ###
\begin{table}[H]
\resizebox{\columnwidth}{!}{\begin{tabular}{m{2cm}cm{2cm}c}
\textbf{Actual} & \textbf{Actual-value}  & \textbf{Supposed} & \textbf{Supposed-value} \\\hline
Skills                     & `r main$value_color[main$Ind=="Sk.0"]`                      &                              &  \\\cline{1-2}
\emph{\% Skill1}           & `r main$value_color[main$Ind=="Sk.1"]`                      &                              &  \\\cline{1-2}
\emph{\% Skill2}           & `r main$value_color[main$Ind=="Sk.2"]`                      & \multirow{-3}{2cm}{Training} & \multirow{-3}{*}{`r main$value_color[main$Ind=="TR.1"]`}\\\cline{1-2}
\multirow{2}{2cm}{Training attendance} & \multirow{2}{*}{`r main$value_color[main$Ind=="TR.a"]`}     & Monitoring                & `r main$value_color[main$Ind=="M.b"]` \\\cline{3-4}
                                       &                                                             & Training feedback         & `r main$value_color[main$Ind=="Tr.f"]` \\\hline
\end{tabular}}
\end{table}
</code></pre>
  • 1
    Hi and welcome. What language is the code you gave us written in? – AndréC Jul 28 '20 at 04:38
  • Its a mix of latex and R. There is 1 R code chunk to create the column value_color in dataframe 'main' - rest is latex. – user3218428 Jul 28 '20 at 04:49
  • Is your problem with the R code or the LaTeX code? – AndréC Jul 28 '20 at 04:56
  • Its with the latex code- the R code is clearly coloring the cells right. In latex, I just cannot paste a coloured cell from the main dataframe into merged cells. – user3218428 Jul 28 '20 at 05:07
  • if you have MS Excel try Excel2LaTeX. It is available on CTAN. https://ctan.org/tex-archive/support/excel2latex – domperor Jul 28 '20 at 05:16
  • As for multirow coluoring, this blog post may help u https://texblog.org/2014/05/19/coloring-multi-row-tables-in-latex/ – domperor Jul 28 '20 at 05:19
  • Unfortunately I cannot manipulate anything in excel- this process is meant to create hundreds of automated reports from csv files downloaded via an API. I had already looked at the link you provided for multirow colouring- it does not solve the issue since the link only helps with creating a new cell with its colour coded in latex. My coloured cell is present in a dataframe column, and it needs to be pasted onto a merged cell in a latex table. – user3218428 Jul 28 '20 at 05:54
  • 1
    If your problem is a LaTeX problem, why do you give the R code here? – AndréC Jul 28 '20 at 06:06
  • 1
    Can you post the Latex code separate from the R-code, so that we could better understand the issue and be able to compile? – hesham Jul 28 '20 at 06:08
  • 2
    You may add a minimal working example (MWE) IN LATEX that illustrates your problem. Reproducing the problem and finding out what the issue is will be much easier when we see compilable code, starting with \documentclass{...} and ending with \end{document}. – hesham Jul 28 '20 at 06:13
  • 1
    I can't get tangled up now with such long example, but to me this is a wrong approach. I will merge the data in the R side to construct data frames to be converted "as is" to LaTeX tables with kable and kableExtra. See https://stackoverflow.com/questions/46242281/how-do-you-change-the-color-of-the-cell-in-kable-output-table-in-knitr – Fran Jul 28 '20 at 06:50
  • The showed Rmarkdown example is not compilable as is. Please reduce your example as far as possible with self-contained source data and check that the pasted code can be exported as is to a PDF. BTW, to color multirow cells in the LaTeX side, see here. – Fran Jul 28 '20 at 10:17
  • @Fran I have been experimenting with flextable, kableextra (cell_spec etc.) and latex to look for the exact kind of tables/document I wanted to produce. Flextable suited me the most- but knitting to pdf was not good. Kableextra is good but complex custom merging in table wasn't working- https://stackoverflow.com/questions/58132626/rmarkdown-can-we-merge-two-cells-with-kableextra. I went for latex finally- if someone can recommend a better way to produce tables with functionalities of conditional cell coloring, rotate text, custom merging, fixed position in pdf document, would be great! – user3218428 Jul 28 '20 at 18:01
  • The part between the --- is not LaTeX; it still has some R stuff in it, so that a good portion of this site can't help you. I'm having trouble following what you mean by "paste". It seems like you're trying to have a multirow cell that is colored. Does that summarize your problem? – Teepeemm Jul 28 '20 at 18:24
  • @Teepeemm you are right- this is an R markdown file. I have corrected the code and the problem appropriately. I also solved the problem using a workaround- I created another column in R dataframe 'color' which only has colour (not text) for the given value of "Ind"- and I pasted this cell in all rows that being merged, except the last one. In the last multirow cell I pasted the 'value_color' column which contains both the text and color. It worked. – user3218428 Jul 29 '20 at 18:42
  • Obviously no one understands your question. If you want an answer, make the effort to reread each comment carefully. Then explain in your question how LaTeX is concerned here since you say that LaTeX code is generated by R code. – AndréC Jul 29 '20 at 18:53
  • I have edited the code properly- it is compiling in a .Rmd file. The latex code is using the R dataframe created in the R code chunk, eg: in Table 1, the term r main$value_color[main$Ind =="M.1a"] is pasted in row 1, column 2. This cell has a number, and is coloured. Similarly I tried to paste r main$value_color[main$Ind=="TR.1"] in a merged multirow cell in Table 2- the cell colour does not extend to all merged cells- that is the problem (as seen in the picture of Table 2 provided here). Hope the problem is clear now. – user3218428 Jul 29 '20 at 19:24

0 Answers0