[R] how to get colnames of a dataframe within a function called by 'apply'

Gabor Grothendieck ggrothendieck at gmail.com
Sat Oct 29 04:25:23 CEST 2005


Iterate over the column names rather than the columns themselves:

par.or <- par(mfrow=c(3,3))
nv <- function(name, data) {
	qqnorm(data[,name], main=name)
	qqline(data[,name], col="red")
	invisible()
}
sapply(colnames(temp), nv, data = temp)
par(par.or)


On 10/28/05, Leo Gürtler <leog at anicca-vijja.de> wrote:
> Hello alltogether,
>
> how is it possible to assign the colnames of a data.frame to a function
> called by apply, e.g. for labeling a plot?
> Example: I want to plot several qqnorm-plots side by side and there
> should be a maintitle for each qqnorm-plot which is identical to the
> respective colname.
> I checked, but the column which is processed by the function called by
> apply does not contain a colname (because by using str() it seems it is
> no column at this point, but just a e.g. numerical vector).
> I also tried with colnames() from within the function, but was not
> successful to get the apropriate colname - either the whole string or
> just the first one.Thus it lacks of a counter that contains the number
> of the row which is processed.
>
> Here is an example code:
>
> <---snip--->
>
> nv <- function(xno.na)
> {
>  par.or <- par(mfrow=c(3,3))
>  qqnorm(xno.na, main="HERE SHOULD BE THE NAME OF THE COLUMN")
>  qqline(xno.na, col="red")
>  par(par.or)
>  print(str(xno.na))
> }
>
>  > temp # just a part of the whole data.frame
>        klarb1    klarb2 abarb laut skla1 skla2
> a      NA 13.068182   7.5    4   0.5   0.5
> b      NA  6.818182   9.0    6    NA   0.5
> c      15.11628  6.818182  10.0    4   1.0   1.5
> d      NA 18.181818  19.0    2   1.0   0.5
>
>  > apply(temp,2,nv)
>
> </---snip--->
>
>
> Thanks a lot!
>
> best wishes,
>
> leo
>
> ______________________________________________
> R-help at stat.math.ethz.ch mailing list
> https://stat.ethz.ch/mailman/listinfo/r-help
> PLEASE do read the posting guide! http://www.R-project.org/posting-guide.html
>




More information about the R-help mailing list