3

Say you have a dataframe such as this:

df <- data.frame("1" = rep(NA,5), "2" = NA, "3" = NA, "4" = NA, "5" = NA, "6" = NA, "7" = NA, "8" = NA, "9" = NA, "10" = NA)
colnames(df) <- c(0:9)
> df
   0  1  2  3  4  5  6  7  8  9
1 NA NA NA NA NA NA NA NA NA NA
2 NA NA NA NA NA NA NA NA NA NA
3 NA NA NA NA NA NA NA NA NA NA
4 NA NA NA NA NA NA NA NA NA NA
5 NA NA NA NA NA NA NA NA NA NA

and you want to add the prefix "d" to the column headers of columns 2, 3, and 4 such that the new column headers are:

> df
   0 d1 d2 d3  4  5  6  7  8  9
1 NA NA NA NA NA NA NA NA NA NA
2 NA NA NA NA NA NA NA NA NA NA
3 NA NA NA NA NA NA NA NA NA NA
4 NA NA NA NA NA NA NA NA NA NA
5 NA NA NA NA NA NA NA NA NA NA

I tried the code from a previously answered question regarding column header prefixes, but it doesn't seem to work (even though the logic makes sense to me):

colnames(df[,c(2:4)]) <- paste("d", colnames(df[,c(2:4)]), sep = "")
Community
  • 1
  • 1
Luke
  • 95
  • 1
  • 1
  • 6

1 Answers1

13

Try

colnames(df)[2:4] <- paste("d", colnames(df[,c(2:4)]), sep = "")

In doing the subsetting of df first, you end up not editing the column names of df itself - but editing the column names of this 'temporary' subset you're playing with. I'm sure someone else can answer this more technically though.

Akhil Nair
  • 3,144
  • 1
  • 17
  • 32
  • Sorry for the follow up 7 years later, but any idea why using a variable the subsetting doesn't work? e.g. colnames(df)[2:ncols(df)] <- paste("d", colnames(df[,c(2:ncols(df))]), sep = "") – user2017023 Jan 27 '22 at 22:57
  • The above works! @user20172023. I couldn't get Akhil's to work. got a `object of type 'closure' is not subsettable` error. – Jacob Baisley Apr 06 '23 at 09:22