Home > Back-end >  add coloured dot in new column using dplyr
add coloured dot in new column using dplyr

Time:02-11

I want to add a colored dot in a new column based on the value of another column.

I have:

data <-
  tibble(
    one = rep("placeholder text",5),
    one_text = 0:4
  )

and can create a new column with a coloured dot using:

black_dot <- "\U2B24"    

data %>%
      flextable %>%
      compose( j = "one",
              value = as_paragraph(
                                  as_chunk(black_dot, props = fp_text(color = "red")
                                           )
                                ),
              part = "body")

I want to pass in the values from column one_text, and have the corresponding colour coded circles in the final frame based on this logic

colour_choice = function(x){
  if (x == 0) {
    "green"
  } else if ( x >= 3) {
    "red"
  } else {
    "orange"
  }
}

when I try:

data %>%
  flextable %>%
  compose( j = "one",
          value = as_paragraph(
                              as_chunk(black_dot, props = fp_text(color = colour_choice( ~ .one_text))
                                       )
                            ),
          part = "body")

I get:

enter image description here

Is there a way to make it so that the cirlces are coloured accordingly?

packages

library(officedown)
library(knitr)
library(tidyverse)
library(flextable)
library(officer)

CodePudding user response:

You can achieve this by vectorizing your colour_choice function:

colour_choice <- Vectorize(colour_choice)

data %>%
  flextable %>%
  compose( j = "one",
           value = as_paragraph(
             as_chunk(black_dot, props = fp_text(color = colour_choice(one_text))
             )
           ),
           part = "body")

which yields

Table with red, green and orange dots

  • Related