Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Rename a set of columns in R by position

Tags:

dataframe

r

I have a data frame where I want to rename 30 out 45 columns. These 30 columns have different names (they come from different sources), but they are always in position 2:31 in the dataframe. Is there a way to rename columns 2:31 something along the lines of names(df)[2:31]<- c("name1", "name2", ..., "name30")? Alternatively, is there a way to use dplyr's rename command without giving the names of the columns and instead give their positions?

I know this is sort of basic, but all solutions I could find wanted the opposite, rename a column with a known name at an unknown position.

like image 362
Joram Avatar asked Oct 27 '25 22:10

Joram


1 Answers

Use the colnames() function

X <- data.frame(bad=1:3, worse=1:3)
colnames(X)[1:2] <- c("name1", "name2")

You can use colnames() and then subset and pass an array with the names. Hope it helps.

like image 128
Gabriel Mesquita Avatar answered Oct 29 '25 11:10

Gabriel Mesquita



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!