LaTeX中kable分组行行名加标后缩进异常及行名加标方法咨询
Hey there, let's work through this problem step by step. I see you tried adding superscripts directly to row names with four$^1$, but that didn't work in LaTeX format—then enabling escape = FALSE fixed the superscript, but broke the indentation from group_rows. Here's how to resolve both issues cleanly:
Recommended Approach: Convert Row Names to a Dedicated Column
The most reliable fix is to move your row names into the first column of your data frame. This keeps group_rows' indentation logic intact while letting you safely add LaTeX superscripts without conflicts.
Step-by-Step Code
First, make sure you have kableExtra installed (it's required for group_rows):
install.packages("kableExtra") library(kableExtra)
Next, restructure your data to include row names as a column, then add the superscript using LaTeX's native \textsuperscript command:
# Create data frame with row names as the first column at2 <- data.frame( Row_Names = c("one", "two", "three", "four\\textsuperscript{1}", "five"), Col1 = 1:5, Col2 = 6:10, Col3 = 11:15 ) # Generate the table with grouping and proper superscripts kable(at2, format = "latex", booktabs = TRUE, escape = FALSE, # Lets LaTeX parse the superscript command col.names = c("", "Col1", "Col2", "Col3") # Hide the column header for row names ) %>% group_rows("First Group", 1, 3) %>% # Group first 3 rows group_rows("Second Group", 4, 5) %>% # Group last 2 rows column_spec(1, bold = TRUE) # Optional: Bold row names to match default style
Why This Works
By turning row names into a regular column, group_rows applies indentation to the entire row (including the row name column) as intended. The \textsuperscript{1} is a valid LaTeX command that gets rendered correctly when escape = FALSE is set, and it doesn't interfere with the grouping indentation logic.
Alternative: Keep Native Row Names (Manual Indentation)
If you really want to stick with native row names, you can use \textsuperscript in the row names and disable automatic indentation from group_rows, then manually indent the rows you need:
at2 <- cbind(1:5, 6:10, 11:15) rownames(at2) <- c("one", "two", "three", "four\\textsuperscript{1}", "five") kable(at2, format = "latex", booktabs = TRUE, escape = FALSE ) %>% group_rows("First Group", 1, 3, indent = FALSE) %>% # Disable auto-indent group_rows("Second Group", 4, 5, indent = FALSE) %>% add_indent(c(2, 3, 5)) # Manually indent rows within groups
Note that this approach is less flexible, especially if your table has many groups or rows.
Why Your Original Code Broke
When you added $^1$ to the row name and used escape = FALSE, the LaTeX compiler tried to parse the $ as math mode—but kable handles row names in a special LaTeX environment that doesn't play nicely with inline math when combined with group_rows' automatic indentation. Switching to \textsuperscript (a text-mode command) and using a dedicated row name column avoids this conflict entirely.
内容的提问来源于stack exchange,提问作者Dayne

