[R] Create data frame from header only

Marc Schwartz marc_schwartz at comcast.net
Tue Aug 5 03:41:16 CEST 2008


on 08/04/2008 07:40 PM Etienne Bellemare Racine wrote:
> Hi all,
> 
> Given a string list,
>     > paste("A",1:5,sep="")
>     [1] "A1" "A2" "A3" "A4" "A5"
> 
> I would like to create an empty data frame using that list as the 
> header, so I can access my data frame column using,
>     > df [ list [ i ] ]
> 
> Anyone ?
> 
> Thanks,
> Etienne

You don't indicate how you might want the column classes to be defined, but:

Cols <- paste("A", 1:5, sep="")

 > Cols
[1] "A1" "A2" "A3" "A4" "A5"


DF <- read.table(textConnection(""), col.names = Cols)

 > DF
[1] A1 A2 A3 A4 A5
<0 rows> (or 0-length row.names)

 > str(DF)
'data.frame':	0 obs. of  5 variables:
  $ A1: logi
  $ A2: logi
  $ A3: logi
  $ A4: logi
  $ A5: logi


Or, as an example of using 'colClasses':

DF <- read.table(textConnection(""), col.names = Cols,
                  colClasses = "character")

 > str(DF)
'data.frame':	0 obs. of  5 variables:
  $ A1: chr
  $ A2: chr
  $ A3: chr
  $ A4: chr
  $ A5: chr



Note from the "Value" section of ?read.table:

Empty input is an error unless col.names is specified, when a 0-row data 
frame is returned: similarly giving just a header line if header = TRUE 
results in a 0-row data frame. Note that in either case tthe columns 
will logical unless colClasses was supplied.


In this case, I am supplying an empty value using textConnection() in 
place of the typical source file name.

HTH,

Marc Schwartz



More information about the R-help mailing list