Re: [R] Extracting column name in apply/lapply

From: Gabor Grothendieck <ggrothendieck_at_gmail.com>
Date: Tue 29 Aug 2006 - 07:31:46 EST

This can be done using a similar style but without a loop by using sapply over the indexes rather than over the columns:

sapply(1:ncol(X), f)
f <- function(i) {...whatever...}

...whatever... can now refer to colnames(X)[i] and X[,i]

On 8/28/06, Sundar Dorai-Raj <sundar.dorai-raj@pdf.com> wrote:
>
>
> Nick Desilsky wrote:
> > Hi,
> >
> > any good trick to get the column names for title() aside from running lapply on the column indexes?
> >
> > Thanks
> >
> > Nick.
> >
> > apply(X[,numCols],2,function(x){
> > nunqs <- length(unique(x))
> > nnans <- sum(is.na(x))
> > info <- paste("uniques:",nunqs,"(",nunqs/n,")","NAs:",nnans,"(",nnans/n,")")
> > hist(x,xlab=info)
> > # --> title("???")
> > })
> >
> >
> >
> > ---------------------------------
> >
> > [[alternative HTML version deleted]]
> >
> > ______________________________________________
> > R-help@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
> > and provide commented, minimal, self-contained, reproducible code.
>
> This is where a for loop is much more useful (and readable):
>
> for(i in numCols) {
> nunqs <- length(unique(X[, i]))
> nnans <- sum(is.na(X[, i]))
> ## `n' is missing from this example
> info <-
> paste("uniques:",nunqs,"(",nunqs/n,")","NAs:",nnans,"(",nnans/n,")")
> hist(X[, i],xlab=info)
> title(colnames(X)[i])
> }
>
> HTH,
>
> --sundar
>
> ______________________________________________
> R-help@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
> and provide commented, minimal, self-contained, reproducible code.
>



R-help@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 and provide commented, minimal, self-contained, reproducible code. Received on Tue Aug 29 09:24:36 2006

Archive maintained by Robert King, hosted by the discipline of statistics at the University of Newcastle, Australia.
Archive generated by hypermail 2.1.8, at Tue 29 Aug 2006 - 10:24:56 EST.

Mailing list information is available at https://stat.ethz.ch/mailman/listinfo/r-help. Please read the posting guide before posting to the list.