1

Data frame with 4 columns and want to replace 2nd and 3rd column names only.

data frame=df
col.names =A,B,C,D
New col.names= Z,F

i have tried with the below code :

colnames(df)[2]<-"Z"
colnames(df)[3]<-"F"

but is there any possibility to rename with single line of code ? Actual data frame contains 150+ colnames, so searching for better solution.

alistaire
  • 42,459
  • 4
  • 77
  • 117

1 Answers1

3

As it is a data.frame, names can also work in place of colnames as names of a data.frame is the column names. Subset the column names with index [2:3] (if it is a range of columns or use [c(2, 3)]) and assign it to the new column names by concatenating (c) names as a vector

names(df)[2:3] <- c("Z", "F")
akrun
  • 874,273
  • 37
  • 540
  • 662