conditional columns using kable

Hello,
I need to specify the col.names in kable according to the number of rows from a table.
I was thinking about using if and ifelse to do it, but I can't reproduce what I want.

data2=datasets::chickwts
data2=data2 %>% mutate(over=weight>200)
tb1=data2 %>% filter(feed=="linseed") %>%group_by(over) %>% count() %>% spread(over,n)
jkl=ncol(tb1)


if (jkl==1) {

  kable(tb1,col.names = c("Blue")) %>%  
    
} else { 

  kable(tb1,col.names = c("Blue","Black")) %>% } 

kable_styling(full_width = TRUE)

The issue is I can't process two kinds of tables. One with 1 column, another with 2.
I wrote this because I need to be able to change only the filer condition and repeat the code without worrying about it.

This is my first thread on this forum section. I hope I posted tall you need in order to understand my case.
Thanks for your time and interest.
Good luck

data2 <- datasets::chickwts %>% 
  mutate(over=weight>200)
tb1 <- data2 %>% 
  filter(feed=="linseed") %>%
  group_by(over) %>% 
  count() %>% 
  spread(over,n)

possible_names <- c("Blue","Black")
names_to_use <- possible_names[1:ncol(tb1)]

  
  kable(tb1,col.names = names_to_use) %>%  
    kable_styling(full_width = TRUE)
1 Like

I think I solve It. I used part of your code nirgrahamuk.
Using the %>% inside the if/else conditional was problematic.
So, I created the list of names at the begging, when I value the number of rows/columns of the future table.
Thanks again.

This topic was automatically closed 7 days after the last reply. New replies are no longer allowed.

If you have a query related to it or one of the replies, start a new topic and refer back with a link.