[R] use of 'apply' for 'hist'

Gabor Grothendieck ggrothendieck at gmail.com
Sat Dec 18 21:22:28 CET 2010


On Sat, Dec 18, 2010 at 11:49 AM, casperyc <casperyc at hotmail.co.uk> wrote:
>
> Hi all,
>
> ##########################################
> dof=c(1,2,4,8,16,32)
> Q5=matrix(rt(100,dof),100,6,T,dimnames=list(NULL,dof))
> par(mfrow=c(2,6))
> apply(Q5,2,hist)
> myf=function(x){ qqnorm(x);qqline(x) }
> apply(Q5,2,myf)
> ##########################################
>
> These looks ok.
> However, I would like to achieve more.
>
> Apart from using a loop,
> is there are fast way to 'add' the titles to be more informative?
>
> that is, in the histograms, I want the titles to be 't distribution with
> dof=' the degrees of freedom.
>
> I have tried
> apply(Q5,2,hist,xnames=dof)
> which does not work;
> apply(Q5,2,hist(,xnames=dof));
> does not work either
>
> and similarly, how do I add titles to qqnorm plot
> to make them informative?

Loop over the column headings rather than over the data itself.  Be
sure that dof has class "character".  Always include set.seed if you
post random numbers to r-help so the results are reproducible.  Always
change the par() back after you are finished.  A number of other
stylistic improvements are shown below as well.  Change main= and
xlab= as you like.

	set.seed(123)
	dof <- as.character(c(1,2,4,8,16,32))
	Q5 <- matrix(rt(100, dof), 100, 6, T, dimnames = list(NULL, dof))
	opar <- par(mfrow = c(2, 6))
	sapply(dof, function(x) hist(Q5[, x], main = x, xlab = ""))
	myf <- function(x) { qqnorm(Q5[, x], main = x, xlab = ""); qqline(Q5[, x]) }
	sapply(dof, myf)
	par(opar)


-- 
Statistics & Software Consulting
GKX Group, GKX Associates Inc.
tel: 1-877-GKX-GROUP
email: ggrothendieck at gmail.com



More information about the R-help mailing list