[S] Summary - changing a variable name (Thanks again)

Barker, Chris {GL P~Palo Alto} (CHRIS.BARKER@roche.com)
Thu, 20 Aug 1998 13:58:10 -0700


Here is a summary of the replies I've received. Again thanks very much.
(Apologies to those whose suggestions I didn't include here, I didn't
want to take up to much bandwidth.)

------------------------------------------------------------------------
---------------------------------------------------------
>From Brian Ripley

names(df)[match("old", names(df)] <- "new"

You need the quotes, but "old" and "new" could be character vectors.
------------------------------------------------------------------------
---------------------------------------------------------

>From Doug Bates

Suppose your dataframe is called myfrm and you want to change the name
of the "foo" column to "bar". It could look like

frmNames <- names( myfrm )
frmNames[ match( "foo", frmNames ) ] <- "bar"
names( myfrm ) <- frmNames
------------------------------------------------------------------------
---------------------------------------------------------
>From Bill Dunlap
change.column.name <- function(data.frame, old.name, new.name) {
i <- match(old.name, names(data.frame))
if (any(is.na(i)))
stop(paste("(some of)", old.name, "not in data.frame"))
names(data.frame)[i] <- new.name
data.frame
}
> x<-data.frame(One=1:3,Two=4:6)
> x <- change.column.name(x, "One", "Alpha")
> x
Alpha Two
1 1 4
2 2 5
3 3 6
> x <- change.column.name(x, c("Two","Alpha"), c("II", "I"))
> x
I II
1 1 4
2 2 5
3 3 6
------------------------------------------------------------------------
---------------------------------------------------------
>From John VanderPloeg

# variable names before changing them
> names(dec)
[1] "DEC1" "DEC2" "count"

#function
> change.varname
function(data.f, var.name, newvar.name)
{
names(data.f)[names(data.f) == var.name] <- newvar.name
data.f
}

#call function changing DEC2 to DEC3
> dec<-change.varname(dec,"DEC2","DEC3")

#new variable names
> names(dec)
[1] "DEC" "DEC3" "count"
------------------------------------------------------------------------
---------------------------------------------------------

Chris Barker
Principal Pharmacoeconomic Statistician
Roche Pharma Business - Palo Alto
(650)-852-3152

-----------------------------------------------------------------------
This message was distributed by s-news@wubios.wustl.edu. To unsubscribe
send e-mail to s-news-request@wubios.wustl.edu with the BODY of the
message: unsubscribe s-news