Skip to content

Instantly share code, notes, and snippets.

@teguhn
Last active November 22, 2016 16:04
Show Gist options
  • Save teguhn/eedee0cf7ebea30d58e327d0f21f0f2b to your computer and use it in GitHub Desktop.
Save teguhn/eedee0cf7ebea30d58e327d0f21f0f2b to your computer and use it in GitHub Desktop.
relative frequency
# v vector input
# relfreq output data.frame of frquency and relative frequency
relfreq <- function(v){
tab.v <- table(v)
result <- cbind(data.frame(tab.v), rel=tab.v/length(v))
result[,4] <- format(round(result[,4]*100, 2), nsmall = 2)
names(result) <- c("var","freq",NA,"relfreq")
return(result[order(-result$freq),c(1,2,4)])
}
# > contoh <- c(1,2,3,5,2,5,2,5,3,6,2,6,3,6,3,6,2,8,2,7,2,7,2,8,3)
# > relfreq(contoh)
# var freq relfreq
# 2 2 8 32.00
# 3 3 5 20.00
# 5 6 4 16.00
# 4 5 3 12.00
# 6 7 2 8.00
# 7 8 2 8.00
# 1 1 1 4.00
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment