Summary Statistics function in R: sumstats()

The following is a bit of code I wrote in R to replicate the results of the des function in STATA. First, run the following code:

R:

# mean.k function
mean.k=function(x) {
if (is.numeric(x)) round(mean(x, na.rm=TRUE), digits = 2)
else "N*N"
}

# median.k function
median.k=function(x) {
if (is.numeric(x)) round(median(x, na.rm=TRUE), digits = 2)
else "N*N"
}

# sd.k function
sd.k=function(x) {
if (is.numeric(x)) round(sd(x, na.rm=TRUE), digits = 2)
else "N*N"
}

# min.k function
min.k=function(x) {
if (is.numeric(x)) round(min(x, na.rm=TRUE), digits = 2)
else "N*N"
}

# max.k function
max.k=function(x) {
if (is.numeric(x)) round(max(x, na.rm=TRUE), digits = 2)
else "N*N"
}

###########################################################

	# sumstats function #

sumstats=function(x) {	# start function sumstats
sumtable = cbind(as.matrix(colSums(!is.na(x))),
sapply(x,mean.k),
sapply(x,median.k),
sapply(x,sd.k),
sapply(x,min.k),
sapply(x,max.k))
sumtable=as.data.frame(sumtable)
names(sumtable)=c("Obs","Mean","Median","Std.Dev","min","MAX")
sumtable
}						# end function sumstats

The function can now be used in the following way (“cps” is the name for my dataframe):

sumstats(cps)
Advertisements
Tags: ,

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

%d bloggers like this: