[R] Bug in colnames of data.frames? -- NOT

Prof Brian Ripley ripley at stats.ox.ac.uk
Tue Aug 17 16:29:14 CEST 2004


This is not a bug, and BTW data frames have names not colnames.
As I have said already today, don't confuse the printed repesentation of 
an object with the object itself.

On Tue, 17 Aug 2004, Arne Henningsen wrote:

> I am using R 1.9.1 on on i686 PC with SuSE Linux 9.0.
> 
> I have a data.frame, e.g.:
> 
> > myData <- data.frame( var1 = c( 1:4 ), var2 = c (5:8 ) )
> 
> If I add a new column by
> 
> > myData$var3 <- myData[ , "var1" ] + myData[ , "var2" ]
> 
> everything is fine, but if I omit the commas:
> 
> > myData$var4 <- myData[ "var1" ] + myData[ "var2" ]
> 
> the name shown above the 4th column is not "var4":
> 
> > myData
>   var1 var2 var3 var1
> 1    1    5    6    6
> 2    2    6    8    8
> 3    3    7   10   10
> 4    4    8   12   12
> 
> but names() and colnames() return the expected name:
> 
> > names( myData )
> [1] "var1" "var2" "var3" "var4"
> > colnames( myData )
> [1] "var1" "var2" "var3" "var4"
> 
> And it is even worse: I am not able to change the name shown above the 4th 
> column:
> > names( myData )[ 4 ] <- "var5"
> > myData
>   var1 var2 var3 var1
> 1    1    5    6    6
> 2    2    6    8    8
> 3    3    7   10   10
> 4    4    8   12   12
> 
> I guess that this is a bug, isn't it?

No.  Take a look at the fourth column more carefully.

> myData[4]
  var1
1    6
2    8
3   10
4   12

> class(myData[4])
[1] "data.frame"

You included a single-column data frame in your data frame.

-- 
Brian D. Ripley,                  ripley at stats.ox.ac.uk
Professor of Applied Statistics,  http://www.stats.ox.ac.uk/~ripley/
University of Oxford,             Tel:  +44 1865 272861 (self)
1 South Parks Road,                     +44 1865 272866 (PA)
Oxford OX1 3TG, UK                Fax:  +44 1865 272595




More information about the R-help mailing list