How do I change the names of the first few columns and leave the remaining as they were if they are not included in range?

Viewed 24

For example I have a dataframe that looks like this

ID| first name| last name| DOB
 1       John      Smith   1/4/1999
 2       Fred   Johnson    1/2/1987

I have a vector that is

c("Identification","First","Last")

I then do

names(df2)<-Vector[1:3]

Which then gives me almost what I want but not exact.

 Identification|First|Last|
 1              John  Smith      1/4/1999
 2               Fred Johnson    1/2/1987

I would like the DOB to not go missing

     Identification|First|Last|DOB
 1              John  Smith      1/4/1999
 2               Fred Johnson    1/2/1987

Is there a way to do this dynamically. Nothing where you decide to add DOB at the end. I want a script that would just change the first three columns based on the selection and leave the remaining columns as their name is and not turn them into blank.

3 Answers

You can use

names(df2)[1:3] <- Vector

If you wanted to change the first element of x to 5, you'd use x[1] <- 5. If you wanted to change the first couple elements of x to 5, 7, you'd use x[1:2] <- c(5, 7). Assignments to names(df) work the same.

colnames(df2) = c(Vector,colnames(df2)[4])

Where 4 is the index of the column that you want to preserve the name.

In the case that you have more than 4 names, you can dynamically rename them:

vector <- c("Identification","First","Last")

names(df) <- c(vector, names(df)[(length(vector)+1):ncol(df)])

Data

df <- data.frame(ID = c(1,2),
                 "first name" = c("John", "Fred"),
                 "last name" = c("Smith", "Johnson"),
                 DOB = c("1/4/1999", "1/2/1987"))
Related