I am trying to create function to generate tables for frequency and percentage for multiple columns.
data<-data.frame(
gender = c(1,2,1,2,1,2,1,2,2,2,2,1,1,2,2,2,2,1,1,1,1,1,2,1,2,1,2,2,2,1,2,1,2,1,2,1,2,2,2),
sector = c(3,3,1,2,5,4,4,4,4,3,3,4,3,4,2,1,4,2,3,4,4,4,3,1,2,1,5,5,4,3,1,4,5,2,3,4,5,1,4),
col1=c(1,1,0,0,0,0,0,0,1,0,0,0,0,0,0,0,0,1,0,0,0,1,1,1,0,1,1,0,0,0,0,1,0,0,0,0,1,0,1),
col2=c(1,1,1,1,1,0,0,0,0,1,1,1,1,1,0,0,0,1,1,1,0,1,1,1,1,1,0,0,0,1,1,1,1,1,1,1,0,0,0),
col3=c(1,1,0,0,0,0,0,1,0,0,0,0,0,0,0,0,1,0,0,0,0,0,1,1,1,0,0,0,1,0,0,1,1,1,1,1,0,0,1),
col4=c(1,0,0,0,0,0,0,0,0,0,1,0,0,0,0,0,0,0,1,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0),
col5=c(1,2,1,1,1,2,1,2,2,1,2,1,1,1,2,2,2,1,1,1,2,1,2,1,1,1,2,2,2,1,1,2,2,1,1,1,2,2,2)
)
data$gender<-factor(data$gender, levels=c(1,2), labels=c("Male","female"))
data$sector<-factor(data$sector, levels=c(1,2,3,4,5), labels=c("TX","CA","NY","LA","WA"))
data$col1<-factor(data$col1, levels=1, labels="Sales")
data$col2<-factor(data$col2, levels=1, labels="OPS")
data$col3<-factor(data$col3, levels=1, labels="Management")
data$col4<-factor(data$col4, levels=1, labels="HR")
data$col5<-factor(data$col5, levels=c(1,2), labels=c("National","Overseas"))
data$gender1 <- ifelse(data$gender == "Male",1,0)
data$total <- ifelse(data$col5 == "National",1,0)
val_lab(data$gender1)<-c("GENDER"=1)
val_lab(data$total)<-c("All Market"=1)
lst <- list(data$gender1,data$total)
I am trying to create a function which can generate tables for frequency and percentage of values in variables.
library(dplyr)
library(expss)
data <- data
var_list <- c("col1","col2","col3")
first_col <- head(var_list,1)
second_col<- tail(var_list,1)
data1<-data[var_list] %>% as.data.frame()
var_lab(colnames(data1)[ncol(data1)]) <- ""
tab1 <- eval(rlang::parse_expr(paste0("tab_cells(data1,mrset(",
first_col ," %to% ",second_col,"))"))) %>%
tab_cols(lst) %>%
fre(lst)
The output should be look like below