在 flextable 中将所有低于阈值的单元格更改为粗体。

huangapple go评论54阅读模式
英文:

in flextable change all cells below threshold to bold face

问题

以下是要翻译的内容:

I have the following sample data and would like to have all values below a certain value, e.g., 0, highlighted in bold. I can do this for individual columns, but not for all columns at once. I have the procedure for changing the font color, for example, but it does not seem so easy to convert the procedure to bold face.

Assuming that a table contains many columns, specifying each column seems very tedious. Also, looping through each column does not seem to be a suitable way to specify each column.

Sample data:

library(flextable)
library(tidyverse)

set.seed(0)
df <- data.frame(a = runif(10, -20, 20),
                 b = runif(10, -20, 20),
                 c = runif(10, -20, 20))

Example Code:

# 对于单个列使值变为粗体
ft <- df %>%
  flextable() %>%
  bold(., ~ a < 0, ~ a, bold = TRUE)

# 对于所有列改变字体颜色
ft <- df %>%
  flextable() %>%
  color(color = function(x){
    out <- rep("black", length(x))
    out[x < 0] <- "red"
    out
  })
英文:

I have the following sample data and would like to have all values below a certain value, e.g., 0, highlighted in bold. I can do this for individual columns, but not for all columns at once. I have the procedure for changing the font color, for example, but it does not seem so easy to convert the procedure to bold face.

Assuming that a table contains many columns, specifying each column seems very tedious. Also, looping through each column does not seem to be a suitable way to specify each column.

Sample data:

library(flextable)
library(tidyverse)

set.seed(0)
df &lt;- data.frame(a = runif(10, -20, 20),
                 b = runif(10, -20, 20),
                 c = runif(10, -20, 20))

Example Code:

# bold face values below threshold for one column
ft &lt;- df %&gt;%
  flextable() %&gt;%
  bold(., ~ a &lt; 0, ~ a, bold = TRUE)

# change font color below threshold for all columns 
ft &lt;- df %&gt;%
  flextable() %&gt;%
  color(color = function(x){
    out &lt;- rep(&quot;black&quot;, length(x))
    out[x &lt; 0] &lt;- &quot;red&quot;
    out
  })

</details>


# 答案1
**得分**: 0

你需要在需要加粗的位置放置一个布尔矩阵,其中为TRUE。

像这样:

x = as.matrix(df)
out = matrix(FALSE, nrow = nrow(x), ncol = ncol(x))
out[x < 0] <- TRUE
ft = df %>%
flextable() %>%
bold(bold = out)


<details>
<summary>英文:</summary>

you have to put a boolean matrix with TRUE in cases to be bold

like this 

x=as.matrix(df)
out=matrix(FALSE,nrow = nrow(x),ncol=ncol(x))
out[x < 0] <- TRUE
ft=df%>%
flextable()%>%
bold(bold=out)


</details>



huangapple
  • 本文由 发表于 2023年2月14日 06:02:21
  • 转载请务必保留本文链接:https://go.coder-hub.com/75441631.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定