Search code examples
rnames

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?


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.


Solution

  • 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.