1

I have a data frame with 563 columns in which I would like to change the names of column variables in all except the first 2 columns using a character vector(Cnames) of length 561. I tried using:

colnames(df[,3:563]) <- Cnames

But nothing happens here. But if I try changing the names of all column variables as follows then renaming works:

CoName <- c("char0", "char01", Cnames)
colnames(df) <- CoName

Can someone tell me why this happens? Thanks in advance.

user3922546
  • 187
  • 1
  • 6
  • 16

1 Answers1

3

You can do

colnames(df)[3:563] <- Cnames

which will work.

I'm not familiar with the R memory model, but I suspect that the call to colnames(df[,3:563]) returns a new, temporary object which has nothing to do with the original data frame. On the other hand, colnames(df) will allow you to directly update the reference in the data frame.

martin
  • 3,149
  • 1
  • 24
  • 35