使用 dplyr 在新列中添加彩色点

add coloured dot in new column using dplyr

我想根据另一列的值在新列中添加一个彩色点。

我有:

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

并且可以使用以下方法创建一个带有彩色圆点的新列:

black_dot <- "\U2B24"    

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

我想传入第 one_text 列的值,并根据此逻辑在最终帧中使用相应的颜色编码圆圈

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

当我尝试时:

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

我得到:

有没有办法让圆圈相应地着色?

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

您可以通过矢量化您的 colour_choice 函数来实现此目的:

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

产生