Function to add names to data frame

Burton Guster picture Burton Guster · Sep 7, 2012 · Viewed 37.8k times · Source

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.

Answer

GSee picture GSee · Sep 7, 2012

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