[R] lapply drops colnames

Gabor Grothendieck ggrothendieck at myway.com
Tue Aug 3 02:48:02 CEST 2004


Jack Tanner <ihok <at> hotmail.com> writes:

> 
> Wolski wrote:
> > What you can do is to extend the column (list) by an addtional attribute 
> attr(mydataframe[i],"info")<-names(mydataframe)[i] and store theyr names in 
it.
> 
> OK, that's brilliant. Any ideas on how to do this automatically for 
> every column in my dataframe? lapply(dataframe... fails for the obvious 
> reason. Should I do something like this, or is for() to be avoided even 
> in this case?
> 
>  > for(i in 1:length(a)) {print(names(a)[i])}


You can also lapply or sapply over indices or even the column names
themselves like this:

data(iris)

# sapplying over indices

res <- sapply(1:ncol(iris), function(i) {
       cat("1st element of", colnames(iris)[i], "is", iris[1,i], "\n")
       iris[1,i]
} )
res

# sapplying over column names

res <- sapply(colnames(iris), function(s) {
       cat("1st element of", s, "is", iris[1,s], "\n")
       iris[1,s]
} )
res




More information about the R-help mailing list