[R] Extracting column name in apply/lapply
Gabor Grothendieck
ggrothendieck at gmail.com
Mon Aug 28 23:31:46 CEST 2006
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 at 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 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
> > 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 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
> and provide commented, minimal, self-contained, reproducible code.
>
More information about the R-help
mailing list