[R] lapply drops colnames

Wolski wolski at molgen.mpg.de
Mon Aug 2 23:27:21 CEST 2004


The (column) - names are a property of the data.frame (list - from which data.frame inherits (at least theoretically (green book) how it is implemented in R I do not know.) The columns of the data.frame are lists again. The data.frama is the box and a column is a list in the data.frame list. lapply is working on list elements. The column list does not know anything about the list (data.frame) in which it is stored. Hence, it does not know also the name (index) at which it is stored. lapply is iterating through this container
 not randomly.
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.
After you have done it you can

lapply(a, function(x) {print(attr(x,"info"))})

Hope it helps.


*********** REPLY SEPARATOR  ***********

On 8/2/2004 at 5:03 PM Jack Tanner wrote:

>>>I want to iterate over a data frame by columns, and as I'm processing 
>>>each column I want to know its column name.
>>> > a <- as.data.frame(list(1,2,3))
>>> > colnames(a) <- c("a", "b", "c")
>>> > colnames(a)
>>>[1] "X1" "X2" "X3"
>>> > lapply(a, function(x) {print(colnames(x))})
>>>What is lapply doing? Why does it drop the column name of every column 
>>>it's iterating over? How can I get the column name as a string?
>>>R-help at stat.math.ethz.ch mailing list
>>>PLEASE do read the posting guide! http://www.R-project.org/posting-guide.html

Dipl. bio-chem. Eryk Witold Wolski    @    MPI-Moleculare Genetic   
Ihnestrasse 63-73 14195 Berlin       'v'    
tel: 0049-30-83875219               /   \    
mail: wolski at molgen.mpg.de        ---W-W----    http://www.molgen.mpg.de/~wolski

More information about the R-help mailing list