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.