[R] names in data.frame

Ott Toomet siim at obs.ee
Tue May 7 10:43:07 CEST 2002


On Tue, 7 May 2002, ken_lee wrote:

  |Dear all,
  |      Sometime I need to change data column name,but I catn't do it.

Hi,

one way to change the column name in data.frame is to use names(). 

> e.g.test<-data.frame(class=c("a","a","a","b","b"),value=1:5)
> names(test)[2] <- "foo"
> test
  class foo
1     a   1
2     a   2
3     a   3
4     b   4
5     b   5

You should ensure that the names are unique.  You can also try a more
intelligent way:

> names(test)[which(names(test)=="foo")] <- "bar"
> test
  class bar
1     a   1
2     a   2
3     a   3
4     b   4
5     b   5

In your example, you may use a similar method, e.g. build a list (remember
that data.frame is actually a list) without the names and thereafter to give
them names:

  |example:
  |     type<-c("max","min")
  |    test<-data.frame(class=c("a","a","a","b","b"),value=1:5)
  |
  |    for (i in 2:length(type)) {
  |        tmp<-gsummary(test,FUN=type[i],groups=test$class)
  |        tmp1<-data.frame(class=tmp$class,   type[i]   =  tmp$value)
  |                                                                             ... error... : I catn't assign "max"   by type[i]
  |   }

tmp1 <- list(tmp$class, tmp$value)
names(tmp1) <- c("class", type[i])
tmp1 <- as.data.frame(tmp1)

should work.

Cheers,

Ott

-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-
r-help mailing list -- Read http://www.ci.tuwien.ac.at/~hornik/R/R-FAQ.html
Send "info", "help", or "[un]subscribe"
(in the "body", not the subject !)  To: r-help-request at stat.math.ethz.ch
_._._._._._._._._._._._._._._._._._._._._._._._._._._._._._._._._._._._._._._._



More information about the R-help mailing list