How does colnames function assign new column names?

蓝咒 提交于 2020-01-14 15:27:30

问题


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.


回答1:


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?



来源:https://stackoverflow.com/questions/58494640/how-does-colnames-function-assign-new-column-names

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!