Skip to content

Instantly share code, notes, and snippets.

@decodebiology
Last active June 7, 2016 16:38
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save decodebiology/609f405ef652b100b3d612d4a9aa3761 to your computer and use it in GitHub Desktop.
Save decodebiology/609f405ef652b100b3d612d4a9aa3761 to your computer and use it in GitHub Desktop.
Calculate confidence interval for multiple columns in a matrix (table) using R function CI_normal and CI_tdist
#USAGE: CI_normal(matrix[,c(x:y)],97.5) - multiple column from a normal distribution
#USAGE: CI_tdist(matrix[,c(x:y)],97.5) - multiple column from a t distribution
#USAGE: CI_normal(matrix[,x],97.5) - single column from a normal distribution
#USAGE: CI_tdist(matrix[,x],97.5) - single column from a t distribution
#Created and updated by Santhilal Subhash on 2016/06/07
CI_normal <- function(li,stat)
{
cat(paste0("CI","\t","column","\t","Lower.limit","\t","Upper.limit","\n"))
if(length(colnames(li))>1)
{
for(i in 1:length(colnames(li)))
{
sample <- colnames(li)
error <- qnorm(stat/100)*sd(li[,i])/sqrt(length(li[,i]))
left <- mean(li[,i])-error
right <- mean(li[,i])+error
cat(paste0(stat,"% norm dist","\t",sample[i],"\t",left,"\t",right,"\n"))
}
}
else{
error <- qnorm(stat/100)*sd(li)/sqrt(length(li))
left <- mean(li)-error
right <- mean(li)+error
cat(paste0(stat,"% norm dist","\tNA","\t",left,"\t",right,"\n"))
}
}
CI_tdist <- function(li,stat)
{
cat(paste0("CI","\t","column","\t","Lower.limit","\t","Upper.limit","\n"))
if(length(colnames(li))>1)
{
for(i in 1:length(colnames(li)))
{
sample <- colnames(li)
error <- qt(stat/100,df=length(li[,i])-1)*sd(li[,i])/sqrt(length(li[,i]))
left <- mean(li[,i])-error
right <- mean(li[,i])+error
cat(paste0(stat,"% t-dist","\t",sample[i],"\t",left,"\t",right,"\n"))
}
}
else{
error <- qt(stat/100,df=length(li)-1)*sd(li)/sqrt(length(li))
left <- mean(li)-error
right <- mean(li)+error
cat(paste0(stat,"% t-dist","\tNA","\t",left,"\t",right,"\n"))
}
}
@decodebiology
Copy link
Author

decodebiology commented Jun 7, 2016

USAGE1: CI_normal(matrix[,c(x:y)],97.5) : multiple column from a normal distribution at 97.5 % CI interval
USAGE2: CI_tdist(matrix[,c(x:y)],97.5) : multiple column from a t distribution at 97.5 % CI interval
USAGE3: CI_normal(matrix[,x],97.5) : single column from a normal distribution at 97.5 % CI interval
USAGE4: CI_tdist(matrix[,x],97.5) : single column from a t distribution at 97.5 % CI interval

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment