用Kable使列名居中并带有换行符

时间:2019-04-04 13:29:57

标签: r formatting centering kable columnname

我在居中包装文字的列名时遇到一些麻烦。换行文本的第一行居中,但第二行不在。

test_data <- data.frame(Mean = runif(5, 3.71, 7.72),
                        N = sample(57:59, 5, replace = TRUE),
                        sd = c(1, rep(0, 4)),
                        d = rep(1, 5),
                        naod = sample(1:4, 5, replace = TRUE),
                        a = sample(5:12, 5, replace = TRUE),
                        sa = sample(37:44, 5, replace = TRUE)
test <-as.data.frame(t(as.matrix(sapply(2:6,function(i) vec_fun5(test_Data,i)))))

kable(test,"latex" ,booktabs=T, align="c",col.names=linebreak(c('Mean','\\textit{N}' ,'Strongly\n Disagree','Disagree','Neither Agree\n or Disagree','Agree','Strongly\n Agree')),row.names = T,escape=F)%>%
  row_spec(0,align = "c")

Output Table

我希望两条线都位于单元格的中心。

1 个答案:

答案 0 :(得分:2)

您可以使用tableHTML

测试数据:

set.seed(1)
test_data <- data.frame(Mean = runif(5, 3.71, 7.72),
                        N = sample(57:59, 5, replace = TRUE),
                        sd = c(1, rep(0, 4)),
                        d = rep(1, 5),
                        naod = sample(1:4, 5, replace = TRUE),
                        a = sample(5:12, 5, replace = TRUE),
                        sa = sample(37:44, 5, replace = TRUE))

library(tableHTML)



test_data %>% 
  tableHTML(round = 2, 
            widths = c(50, 50, 50, 50, 
                       80, 120, 50, 50),
            headers = c("Mean", "N",
                        "Strongly <br>Disagree",
                        "Disagree",
                        "Neither Agree <br> or Disagree",
                        "Agree",
                        "Strongly <br>Agree"),
            escape = FALSE) %>% 
  add_theme("scientific")

结果如下:

output