开发者

Change column name by looking up

I know that I can change a data.frame column name by:

colnames(df)[3] <- "newname"

But there might be cases where the column I want to change is not in the 3rd position. Is there a way to look up the column by name and change it? Like this...

colnames(df)[,"oldname"] <- "newname"

B开发者_Go百科TW, I have tried this code and I keep getting incorrect number of subscripts on matrix.

Thanks.


colnames(df)[colnames(df)=="oldname"] <- "newname"

or just names

names(df)[names(df)=="oldname"] <- "newname"

There are various functions for renaming columns in packages as well.


colnames(df)[colnames(df)=="oldname"] <- "newname"

or

names(df)[names(df)=="oldname"] <- "newname"

(since names and colnames are equivalent for a data frame)

or you might be looking for

library(reshape)
df <- rename(df,c(oldname="newname"))


I was using package data.table today and when I tried to change a column name using my usual method a message appeared recommending this approach:

library(data.table)

df <- read.table(text= "
          region    state  county
             1        1       1  
             1        2       2  
             1        2       3 
             2        1       4
             2        1       4
", header=TRUE, na.strings=NA)

df

setnames(df, "county", "district")

df


A somewhat more general approach that will replace all of the "old"s at the beginning of any current name with "new" in the same character location:

names(df) <- sub("^old", "new", names(df) )
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜