【问题标题】:R: Removing row from data table causes kable errorR:从数据表中删除行会导致 kable 错误
【发布时间】:2020-11-28 02:17:33
【问题描述】:

非常感谢您!

我正在尝试读入一个 csv 文件,去掉第一行并使其成为字符向量,然后使用 kable 打印表格,使用 kableExtra 的 add_header_above 将第一行添加回作为二级标题。

当我执行以下代码时,我得到了这个错误:

htmlTable_add_header_above(kable_input, header, bold, italic, 中的错误:您提供的新标题行与原始 kable 输出的总列数不同。

如果我删除 table13 行,代码可以正常工作并打印表格,但标题当然会出现两次。

table13 <- read.csv("tables/table.csv", header=FALSE)
## Read the table

second_level_header <- table13  [1,]
second_level_header <- as.vector(unlist(second_level_header),mode="character")
## Remove the first line of the table and make it a character vector 

first_level_header <- table13 [2,]
first_level_header <- as.vector(unlist(first_level_header),mode="character")
## Take the second line of the table and do the same

colnames(table_13) <- first_level_header
## The second line of the table becomes the column names

table13 <- table13 [3:nrow(table13),]
# Remove the first two lines since the second line is now the column names and the first line will be the second-level header

knitr::kable(
  table_13, 
  col.names = gsub("[.]", " ", names(table_13))
) %>% add_header_above(second_level_header)
# Print the table

如果我只是将 table13 打印到控制台,我会得到以下信息。我认为问题在于行名被认为是一个额外的“列”,但我不知道如何摆脱它们以便 add_header_above 看到正确的列数。

                                                                      Risk Likelihood of risk Minimum
3                                            Material is late or defective                80%    100%
4 Complex airframe producibility will lead to increased manufacturing time                 25     100
5                                               GFI deliveries are delayed                 20      90
6                    Hiring and retention are affected by changing economy                 15      95
  Most likely Maximum
3        105%    130%
4         110     125
5         100     115
6         110     135

【问题讨论】:

    标签: r kable


    【解决方案1】:

    啊哈!回答了我自己的问题。无论出于何种原因,我都需要积极抑制 kable 中的行名:

    knitr::kable(
      table13, 
      col.names = gsub("[.]", " ", names(table13)), row.names=FALSE,
    ) %>% add_header_above(second_level_header)
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2021-07-25
      • 2022-11-13
      • 2020-01-04
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2020-03-15
      • 2022-11-14
      相关资源
      最近更新 更多