Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

assign headers based on existing row in dataframe in R

Tags:

dataframe

r

names

After transforming a dataframe, I would like to assign heads/names to the columns based on an existing row. My headers are currently:

row.names   X2  X3  X4  X5  X6  X7  X8  X9  ... 

I would like to get rid of that and use the following row as column headers (without having to type them out since I have many).

The only solution I have for this is to export and re-load the data (with header=T).

like image 744
user3166363 Avatar asked Jan 06 '14 17:01

user3166363


People also ask

How do I reference a header of a Dataframe in R?

colnames() function in R is used to set headers or names to columns of a dataframe or matrix. Syntax: colnames(dataframe) <- c(“col_name-1”, “col_name-2”, “col_name-3”, “col_name-4”,…..)

How do I assign a name to a row in R?

A data frame's rows can be accessed using rownames() method in the R programming language. We can specify the new row names using a vector of numerical or strings and assign it back to the rownames() method. The data frame is then modified reflecting the new row names.

How do I make the first row a header in a Dataframe in R?

how can make the first row 'zip, cucurrent, pacurrent...' to be the column header? A dput() of the table would help. But you can do a colnames(dat) <- as. character(dat[1,]) to set the column names and normal R syntax to "delete" the first row.


2 Answers

The key here is to unlist the row first.

colnames(DF) <- as.character(unlist(DF[1,])) DF = DF[-1, ] 
like image 86
Vishnu Jayanand Avatar answered Sep 21 '22 17:09

Vishnu Jayanand


Try this:

colnames(DF) = DF[1, ] # the first row will be the header DF = DF[-1, ]          # removing the first row. 

However, get a look if the data has been properly read. If you data.frame has numeric variables but the first row were characters, all the data has been read as character. To avoid this problem, it's better to save the data and read again with header=TRUE as you suggest. You can also get a look to this question: Reading a CSV file organized horizontally.

like image 24
Ricardo Oliveros-Ramos Avatar answered Sep 21 '22 17:09

Ricardo Oliveros-Ramos