colnames函数如何分配新的列名? [英] How does colnames function assign new column names?

查看:130
本文介绍了colnames函数如何分配新的列名?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我已经使用了很多次此功能,但直到现在才想到为什么它起作用?".R的colnames()函数如何为数据框分配新的列名?我的意思是我知道colnames(df)将如何返回数据框的列名.但是如何分配新的呢?

  aa<-mtcars姓氏(aa)colnames(aa)<-字母[1:ncol(aa)]姓氏(aa)#^ colnames函数如何返回列名称或分配新名称?这只是一个功能.#但我们不能通过这种方式更改列数:ncol(aa)ncol(aa)<-10 

目前,colnames函数为:

 函数(x,do.NULL = TRUE,前缀="col"){如果(is.data.frame(x)&& do.NULL)返回(名称(x))dn<-dimnames(x)如果(!is.null(dn [[2L]]))dn [[2L]]别的 {nc<-NCOL(x)如果(do.NULL)空值否则(nc> 0L)paste0(前缀,seq_len(nc))else character()}}<字节码:0x00000000091f1710><环境:名称空间:基础> 

Q: 我看不到这是如何为数据框分配新列名的.

=-左侧的

R中的替换功能是什么?

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.

解决方案

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?

这篇关于colnames函数如何分配新的列名?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆