3

I've used this function so many times but only now thought 'why does it work?'. How can R's colnames() function assign new column names to a data frame? I mean I get how colnames(df) will return the column names of a data frame. But how can it also assign new ones?

aa <- mtcars
colnames(aa)
colnames(aa) <- LETTERS[1:ncol(aa)]
colnames(aa)
# ^ how can colnames function either return column names or assign new ones? It's just a function.

# but we can't change the number of columns this way:
ncol(aa)
ncol(aa) <- 10

As at now the colnames function is:

function (x, do.NULL = TRUE, prefix = "col") 
{
    if (is.data.frame(x) && do.NULL) 
        return(names(x))
    dn <- dimnames(x)
    if (!is.null(dn[[2L]])) 
        dn[[2L]]
    else {
        nc <- NCOL(x)
        if (do.NULL) 
            NULL
        else if (nc > 0L) 
            paste0(prefix, seq_len(nc))
        else character()
    }
}
<bytecode: 0x00000000091f1710>
<environment: namespace:base>

Q: I can't see how this is assigning new column names to data frame.

M--
  • 25,431
  • 8
  • 61
  • 93
jc52766
  • 159
  • 2
  • 9

1 Answers1

5

colnames on the left hand side of a <- is not the same function as on the right hand side. The former is called a replacement function and its name is colnames<-.

Displaying source

You can see its code by typing this at the R console:

`colnames<-`

The source displayed by that looks like this:

`colnames<-` <- function(x, value) { ...modify x...; x }

where the first argument x refers to the argument on the left hand side and the second argument, value, is the right hand side of the <-. They are both input to the replacement function and then R assigns the result of running the replacement function back to x.

Simple example of replacement function

For example, here is a simple replacement function:

# define simple replacement function
`add_n<-` <- function(x, value) x + value  

# test
my_number <- 4
add_n(my_number) <- 3
my_number
## [1] 7

More info

There is some discussion of replacement functions here: What are Replacement Functions in R?

G. Grothendieck
  • 254,981
  • 17
  • 203
  • 341