I have some survey data in which columns correspond to elements and rows, correspond to clients telling how likely they are to buy each element. Looks like that:
item1 = c("Likely", "Unlikely", "Very Likely","Likely") item2 = c("Likely", "Unlikely", "Very Likely","Unlikely") item3 = c("Very Likely", "Unlikely", "Very Likely","Likely") df = data.frame(item1, item2, item3)
I want the pivot table to give the percentage of each response for each item. Right now I am using table () for each column for this process, and its a lot of code to control. How to do this using plyr or apply or something faster?
Current solution:
d1<-as.data.frame(table(df$item1)) d1$item1_percent<- d1$Freq/sum(d1$Freq) names(d1)<-c("Response","item1_freqs","item1_percent") d2<-as.data.frame(table(df$item2)) d2$item2_percent<- d2$Freq/sum(d2$Freq) names(d2)<-c("Response","item2_freqs","item2_percent") d3<-as.data.frame(table(df$item3)) d3$item3_percent<- d3$Freq/sum(d3$Freq) names(d3)<-c("Response","item3_freqs","item3_percent") results<-cbind(d1,d2[,2:3],d3[,2:3])
Note. I really don't need frequency values, just percentages.
Thanks in advance!
source share