Home > front end >  change in the structure of table
change in the structure of table

Time:05-13

I was required a function which can give the required result below, transpose of the current output table.

the output currently i am getting enter image description here

but the required output should be rowlabels in column and column labels in row enter image description here

library(expss)
data(mtcars)
mtcars1 <- mtcars
mtcars1$dd <- ifelse(mtcars1$gear == 4,1,NA)
mtcars1$ff <- ifelse(mtcars1$gear == 5,1,NA)


mtcars1$vs<-factor(mtcars1$vs, levels=c(0,1), labels=c("Male","female"))
mtcars1$am<-factor(mtcars1$am, levels=c(0,1), labels=c("Male","female"))


val_lab(mtcars1$dd)<-c("Local"=1)
val_lab(mtcars1$ff)<-c("Regional"=1)

mk <- with(mtcars1,list(total(),dd, ff))

fun1<- function(dataset,varlist,banner){
  intermediate_table = dataset %>% 
    tab_cols(banner)
  for(each_var in varlist){
    intermediate_table = intermediate_table %>% 
      tab_cells("|" = get(each_var)) %>% 
      tab_stat_cpct(label = each_var)
  }
  intermediate_table %>% 
    tab_pivot(stat_position = "inside_columns")
}

t1 <- fun1(dataset=mtcars1, varlist=c("vs","am"),banner=mk)

CodePudding user response:

As you cell vars in the same dimension with banners it is better to use tab_rows and then tab_transpose:

fun1<- function(dataset,varlist,banner){
    intermediate_table = dataset %>% 
        tab_rows(banner)
    for(each_var in varlist){
        intermediate_table = intermediate_table %>% 
            tab_cells("|" = get(each_var)) %>% 
            tab_stat_cpct(label = each_var)
    }
    intermediate_table %>% 
        tab_pivot(stat_position = "inside_columns") %>% 
        tab_transpose()
}

t1 <- fun1(dataset=mtcars1, varlist=c("vs","am"),banner=mk)

t1
  • Related