当前位置: 动力学知识库 > 问答 > 编程问答 >

r - Function to add names to data frame

问题描述:

I'm have a data frame without columns:

df<-data.frame(v1=c(1:10), v2=seq(1, 100, length=10))

I want to change the header names to "X" and "Y"

I know I can do this using:

names(df)<-c("X","Y")

What I would like to do is write a function where I could pass a data frame as an argument, and place the headers with these header names.

I've tried:

get.names<- function(x)

{names(x)<-c("X", "Y")}

Thanks in advance for any help.

网友答案:

Your function sets the names; you just need to return the object.

get.names<- function(x) {
    names(x)<-c("X", "Y")
    x
}

Alternatively, you could use the setNames function

> setNames(data.frame(v1=c(1:10), v2=seq(1, 100, length=10)), c("X","Y"))
    X   Y
1   1   1
2   2  12
3   3  23
4   4  34
5   5  45
6   6  56
7   7  67
8   8  78
9   9  89
10 10 100
网友答案:

There is an R function which already does this, although instead of modifying the data frame your environment, it returns the renamed data frame:

df<-`names<-`(df, new_names)

In fact, you are already using this function, in a roundabout way, when you call names(df)<- ...


Note that almost no functions in R modify the values they have been passed - almost all are 'functional' in style - performing the changes to a new copy and returning that. For this reason you should expect to see and write lots of code in the form: x=f(x).


Another technique you may find useful is the rename function in the reshape package:

df<-rename(df,c(v1="X", v2="Y"))

Which just changes the names of the specified columns. It also works to rename names in lists and vectors!

网友答案:

If you wish to side-step the internal copying with names<- and df<-rename(df,c(v1="X", v2="Y")) and setNames you can use the data.table package

# some example data
library(data.table)
DF <- data.frame(a = 1:5, b = 1:5)
DT <- data.table(DF)

You can set the names of a data.table by reference (without copying) using setnames

setnames(DT, new = c('new_name1','newname2'))
DT
   new_name1 newname2
1:         1        1
2:         2        2
3:         3        3
4:         4        4
5:         5        5
# you can change only a subset by defining old and new
setnames(DT, old = 'new_name1', new = 'blah')
DT
        blah newname2
1:         1        1
2:         2        2
3:         3        3
4:         4        4
5:         5        5

If you don't want to use data.tables, you can use the setattr function from data.table package (which is very like the function of the same name in the bit package)

setattr(DF, 'names', c('oh','look'))
DF

  oh look
1  1    1
2  2    2
3  3    3
4  4    4
5  5    5

 bit::setattr(DF, 'names', c('yip','hee'))
DF
  yip hee
1   1   1
2   2   2
3   3   3
4   4   4
5   5   5
分享给朋友:
您可能感兴趣的文章:
随机阅读: