[R] How to make sub-headers in R

Boris Steipe boris.steipe at utoronto.ca
Fri May 15 16:53:57 CEST 2015


On May 15, 2015, at 9:55 AM, Liao, Hongsheng <HLiao at odu.edu> wrote:

> I know how to make one-row header for a data frame using "colnames".  Is there any function to insert sub-header between the first row of the data and the header?  Thanks

The elements of a data frame's columns are all of the same type. Inserting an extra row with character values would coerce the entire column to be of type character:

myDf <- data.frame(a=c(1:3),b=letters[1:3], C=LETTERS[1:3], stringsAsFactors=FALSE)
sapply(myDf, class)
          a           b           C 
  "integer" "character" "character" 
myDf <- rbind(c("text1", "text2", "text3"), myDf)
myDf
      a     b     C
1 text1 text2 text3
2     1     a     A
3     2     b     B
4     3     c     C

sapply(myDf, class)
          a           b           C 
"character" "character" "character" 

In addition, you shouldn't be thinking about the "header" as being a textual description anyway: the colname is actually much like a variable name, a label to identify a column. If you think of an Excel file (I think this is where your question is coming from), the names are the A, B ... Z, AA, AB ... names. It just so happens that R can construct column names from data it finds in a "header row". But they are _attributes_ of the data frame, not part of the contents. However you can look at the attributes ...
attributes(myDf)
$names
[1] "a" "b" "C"

$row.names
[1] 1 2 3 4

$class
[1] "data.frame"

attributes(myDf)$names
[1] "a" "b" "C"


... and you can add additional attributes:

attributes(myDf)$subheaders <- c("text1", "text2", "text3")

attributes(myDf)
$names
[1] "a" "b" "C"

$row.names
[1] 1 2 3 4

$class
[1] "data.frame"

$subheaders
[1] "text1" "text2" "text3"


Hope this helps.
Boris







> 
> Hongsheng (Hank) Liao, PhD.
> Lab Manager
> Center for Quantitative  Fisheries Ecology
> Old Dominion University
> 757-683-4571
> 
> 
> 
> 
> 	[[alternative HTML version deleted]]
> 
> ______________________________________________
> R-help at r-project.org mailing list -- To UNSUBSCRIBE and more, see
> 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