daszlosek
daszlosek

Reputation: 1505

Using a for loop with knitr::kable and kableExtra::add_header_above

I am using R version 3.5.2.

I would like to evaluate a string in a kable function, but I am having some issues. Normally, I can pass a string through a for loop using the get function but in the kableExtra::add_header_above function I get the following error:

Error: unexpected '=' in:"print(kable(df4,"html", col.names = c("zero","one")) %>% add_header_above(c(get("string") ="

I have tried a handful of techniques like creating a string outside of the kable function and calling it, using page breaks and print statements in the knit loop and trying the eval function as well. I have also added result ="asis" as suggested here

Here is a reproducible example:

```{r  results="asis"}    
library("knitr")
    library("kableExtra")

    df1 <- mtcars %>% dplyr::select(am,vs)

    df1a <- df1 %>% mutate(type = "A")
    df1b <- df1 %>% mutate(type = "B")
    df1c <- df1 %>% mutate(type = "C")

    df2 <- rbind(df1a,df1b,df1c)

    vector <- as.vector(unique(df2$type))

    for (variable in vector) {

      df3 <- df2 %>% filter(type == (variable))

      df4 <- table(df3$am,df3$vs)

    print(kable(df4,"html", col.names = c("zero","one")) %>%
      add_header_above(c(get("string") = 3)))

    }
```

Ideally, I would like the header of the table to have the string name from the column type. Below is an example of what I want it to look it:

print(kable(df4,"html", col.names = c("zero","one")) %>%
  add_header_above(c("A" = 3)))

I understand that the knitr function needs to be treated differently than regular R when using loops as found in this solution but I am still struggling to get the string to be evaluated correctly. Perhaps because the function requires a vecotr input, it is not evalauting it as a string?

Upvotes: 0

Views: 2016

Answers (1)

Alejandro Andrade
Alejandro Andrade

Reputation: 2216

You have to define your header as a vector. The name of the header should be the names of the vector and the value of the vector would be the number of columns the header will use. The loop in the code should look like this:

for (variable in vector) {
  df3 <- df2 %>% filter(type == (variable))
  df4 <- table(df3$am,df3$vs)
  header_temp = 3
  names(header_temp) = get("variable")
  print(kable(df4,"html", col.names = c("zero","one")) %>%
    add_header_above(header_temp))
}

So first I define the number of columns the of the header in the variable header_temp and then i assign a name to it.

Upvotes: 1

Related Questions