cross_tab summary for Multi response table

I am trying to create a cross tab summary for multi-response table.I am not able to create an exact summary with my function. I am confused with the approach and am not able to find a systematic approach.

Please help or if you have any solution.

data for multi-response table

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,0,1,1,1,0,1,0,0,1,0,1,1,1,0,0,0,1,1,1,0,1,0,1,1,1,0,0,0,1,1,0,0,1,1,1,0,0,0)
)
)

I am able to create these function but doesn't work

newfreq <- function(data,cut_var,var){
  T0<-table(data[[cut_var]],data[[var]])
  T1<-as.data.frame.matrix(T0)
  T1[,"Revenue"]<-row.names(T1)
  T1
}


multi_choice<- function(data,var,grp_var){
  
  data<-data%>% select(grp_var,var)
  
  data$total_column<-NA^!rowSums(!is.na(data[,2:ncol(data)]))
  lst1 <- lapply(names(data[,2:ncol(data)]), function(x) newfreq(data,grp_var,x))
  lst1 <- lst1[!sapply(lst1, is.null)]
  merge.all <- function(x, y) {
    merge(x, y, all = TRUE, by = "Revenue")
  }
  T3 <- Reduce(merge.all, lst1)
  T4<-rbind(c("Overall",colSums(T3[,2:ncol(T3)])),T3)  
  T4[,2:ncol(T4)]<- sapply(T4[,2:ncol(T4)],as.numeric)
  # for(col in names(T4)[c(-1,-ncol(T4))]){
  # T4[col]=(T4[col]*100)/(T4[,ncol(T4)])
  
  #  }
  for(t in names(T4)[c(-1,-ncol(T4))]){
    T4[t]=ifelse(T4[,ncol(T4)]<3,"--",roundUp(T4[,t]))}
  
  names(T4)[names(T4)==names(T4[ncol(T4)])]<-"Total"
  
  T5<-as.data.frame(t(T4))
  header<-T4[[1]]
  T5<-T5[-1,]
  colnames(T5)<-header
  T5 
} 

I am applying function like below

data<- data%>% select(gender,col1,col2,col3)
multi_choice(data,,"gender")

for example The output should be like

image

This topic was automatically closed 21 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.