You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何用formattable/kableExtra修改表格行样式:移除最后一行颜色条

Solution: Remove Color Bars from the Last Row of Your Table

Got it, let's adjust your code so the final row of your table keeps plain numeric values instead of the color bars. The key is to add a conditional check to only apply the color_bar() function to rows that aren't the last one. Here's the updated code:

data(mtcars)
library(knitr)
library(kableExtra)
library(formattable)
library(dplyr)
library(stringr)

mtcars[1:5, 1:4] %>%
  mutate(
    car = row.names(.),
    # Use across() to apply conditional formatting to all numeric columns
    across(c(mpg, cyl, disp, hp), 
           ~ifelse(row_number() == n(),  # Check if we're on the last row
                   .,                     # Keep raw value if yes
                   color_bar("lightgreen")(.)  # Apply color bar if no
           )
    )
  ) %>%
  select(car, everything()) %>%
  kable("html", escape = FALSE) %>%  # Need escape=FALSE to render the color bars
  kable_styling()

Key Details:

  • row_number() == n(): This checks if the current row is the last one in the data frame (n() returns the total number of rows).
  • across(c(mpg, cyl, disp, hp)): Lets us apply the same conditional logic to all your target columns in one go, instead of writing separate lines for each column.
  • escape = FALSE in kable(): Critical for rendering the HTML generated by color_bar() correctly—without this, you'll see raw HTML code instead of the colored bars.

When you run this, the first 4 rows will have the lightgreen color bars, and the 5th (last) row will show just the original numbers with no formatting.

内容的提问来源于stack exchange,提问作者Nicolas

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.25 07:20:39