Skip to content

count each answer category in each column

1 message · arun

#
Hi,
Try this:
dat1<- read.table(text="
ID?? Gender?? Age?? Rate
?A?????? Female??? 0-10?? Good
? A????? Male??????? 0-10?? Good
? B?????? Female???? 11-20? Bad
?B?????? Male???????? 11-20? Bad
?? C?????? Male???????? >20???? N/A
",sep="",header=TRUE,stringsAsFactors=FALSE,na.strings="N/A")
library(plyr)
library(reshape2)

?lst1<-lapply(list(c(3,4),c(2,4),c(2,3)),function(i) mutate(dcast(melt(dat1[,-i],id.var="ID"),value~ID,length),var=rowSums(cbind(A,B,C))))
?lst2<-lapply(seq_along(colnames(dat1)[-1]),function(i) {x1<-lst1[[i]]; colnames(x1)[5]<- colnames(dat1)[i+1]; colnames(x1)[1]<-"Var1";x1[,c(1,5,2:4)]})
names(lst2)<- colnames(dat1)[-1]
?lst2
#$Gender
?# ? Var1 Gender A B C
#1 Female????? 2 1 1 0
#2?? Male????? 3 1 1 1

#$Age
?#? Var1 Age A B C
#1? 0-10?? 2 2 0 0
#2 11-20?? 2 0 2 0
#3?? >20?? 1 0 0 1

#$Rate
?# Var1 Rate A B C
#1? Bad??? 2 0 2 0
#2 Good??? 2 2 0 0
#3 <NA>??? 1 0 0 1
A.K.