R新手使用kable与kableExtra报错:kable_input缺失或未找到
Hey there! Let's fix this kableExtra issue you're having. The core problem is how you're passing the kable-generated table to kable_styling—right now, you're running the two functions as separate commands instead of linking them together.
Let's break down your errors first:
- First error:
kable_styling()requires akable_inputargument (the table object created byknitr::kable()), but you didn't pass anything to it. Runningknitr::kable()andkable_styling()as separate lines means the table output fromkable()isn't being sent tokable_styling(). - Second error: You tried adding
kable_inputas an argument, but you never defined whatkable_inputis—R thinks it's a function that doesn't exist, hence the "could not find function" message.
Here are two working solutions:
Solution 1: Use the pipe operator (%>%) to chain commands
Since you already loaded dplyr, you can use its pipe operator to pass the kable table directly into kable_styling:
{r echo=FALSE} library(readxl); library(dplyr); library(kableExtra); library(knitr) Froot <- read_excel("~/Documents/Project1/Fruit.xlsx") knitr::kable(Froot[1:4]) %>% kable_styling(bootstrap_options = c("striped", "hover", "condensed"))
The %>% takes the output of knitr::kable() and feeds it into kable_styling() as the kable_input argument automatically.
Solution 2: Store the kable table in a variable first
If you prefer not to use pipes, save the table to a variable and pass that variable to kable_styling:
{r echo=FALSE} library(readxl); library(dplyr); library(kableExtra); library(knitr) Froot <- read_excel("~/Documents/Project1/Fruit.xlsx") # Save the kable table to a variable my_fruit_table <- knitr::kable(Froot[1:4]) # Pass the variable to kable_styling kable_styling(kable_input = my_fruit_table, bootstrap_options = c("striped", "hover", "condensed"))
Important note about your chunk option:
Your original chunk used include=FALSE—this will hide all output (including the table) from your final document. If you want to show the table but hide the code, use echo=FALSE instead. If you want to show both code and table, just remove the include=FALSE option entirely.
Bonus: Add extra styling (optional)
Once you have the basic table working, you can chain more kableExtra functions to customize it further, like adding a caption or adjusting column widths:
{r echo=FALSE} knitr::kable(Froot[1:4], caption = "First 4 Rows of the Fruit Dataset") %>% kable_styling(bootstrap_options = c("striped", "hover", "condensed")) %>% column_spec(1, width = "12em") # Adjust width of first column
内容的提问来源于stack exchange,提问作者Marie Bull

