Search code examples
rdataframenames

Renaming columns of data.frame


I came across a solution for renaming the column names of a data.frame:

names(data) <- c("new_name", "another_new_name")

Here is an example:

empl <- c("Mike", "Steven")
wa <- c(25000, 30000)
data <- data.frame(empl, wa)
data

# now rename the columns of the dataframe
names(data) <- c("employee", "wage")
data

Now I am wondering how it is possible to assign a vector to a function-call. The result of names(data) is a vector with chars. And it seems that this vector is not linked in any way to the data.frame.

Can anyone enlighten me what the mechanisms are?

Trying to explain to myself

names(data) <- c("employee", "wage")

Looking at the assignment above:

  • the left hand side names(data) returns a vector with the old column names.
  • does this assignment not assign to a vector? Instead of to a dataframe‘s attribute?

Solution

  • Nice question I think. This is how R interpreter works, which calls Replacement functions. you can define function function<- to set functionality for replacement.

    Let I have this function:

    members_of <- function(x){
      print(x)
    }
    

    I can call it easily:

    members = c("foo", "bar", "baz")
    members_of(members)
    # output
    # [1] "foo" "bar" "baz"
    

    But lets define members_of<- function using back tick character and tmp and value arguments:

    `members_of<-` = function(tmp, value){
         tmp = value
     }
    

    Now I can assign to function call:

    members = c("foo", "bar", "baz")
    # output 
    # [1] "foo" "bar" "baz"
    #
    members_of(members) = c("foo2", "bar2", "baz2")
    # Now values of members will be
    # members
    # [1] "foo2" "bar2" "baz2"