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

PowerBI中grid.table重复行表头的实现方法求助

Got it, let's fix this for you! The key issue here is that grid.table (from the gridExtra package) defaults to merging cells with identical content, which is why your variable names only show up once instead of repeating for every row. Plus, we need to ensure those variable names are bolded as you requested. Here's how to build that custom grob output:

First, let's make sure we have the right data structure and load required packages:

library(gridExtra)
library(reshape2)

# Your original dataset
dataset <- data.frame(
  BDS_ID = c("001","002"), 
  PRIORITY = c("high","medium"), 
  STATUS = c("onair","onair"), 
  COMPANY = c("airfr","fly")
)

# Melt to long format (we'll keep only variable and value for the final output)
my.result <- melt(dataset, id = c("BDS_ID"))[, c("variable", "value")]

Next, we'll create a custom theme for the table grob. This theme will:

  • Make all variable names (first column) bold
  • Use alternating row backgrounds for readability
  • Hide default column headers (since we want variable names to act as row-level labels)
  • Align content to the left for clean formatting
mytheme <- ttheme_default(
  base_size = 10,
  core = list(
    fg_params = list(
      hjust = 0, 
      x = 0.01,
      # Apply bold font only to the first column (variable names)
      fontface = c(rep("bold", nrow(my.result)), rep("plain", nrow(my.result)))
    ),
    bg_params = list(
      # Alternate row backgrounds
      fill = rep(c("white", "grey90"), each = nrow(my.result))
    )
  ),
  # Hide default column headers since we don't need them
  colhead = list(fg_params = list(col = "white"))
)

Finally, build and draw the table grob. We'll also adjust the first column width to fit the longest variable name perfectly:

# Create the table grob, omit column headers
tg <- tableGrob(my.result, cols = NULL, theme = mytheme)

# Adjust first column width to match the longest variable name
tg$widths[1] <- unit(max(nchar(as.character(my.result$variable)))*0.1, "inches")

# Draw the final output
grid.draw(tg)

This will produce exactly the format you wanted:

PRIORITY high
PRIORITY medium
STATUS onair
STATUS onair
COMPANY airfr
COMPANY fly

As for why t(dataset) didn't work: transposing gives you a wide-format table where each variable name appears once (as a row name) with two values next to it, which doesn't match your goal of having each value paired with its full variable name on a separate row.

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.15 08:34:39