Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Function to add names to data frame

Tags:

dataframe

r

names

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.

like image 468
Burton Guster Avatar asked Sep 06 '12 22:09

Burton Guster


1 Answers

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
like image 188
GSee Avatar answered Nov 22 '22 21:11

GSee