Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

use first row data as column names in r

Tags:

r

names

I have a dirty dataset that I could not read it with header = T. After I read and clean it, I would like to use the now first row data as the column name. I tried multiple methods on Stack Overflow without success. What could be the problem?

The dataset t1 should look like this after clean up:

      V1    V2  V3  V4  V5 1   col1    col2    col3    col4 2   row1    2   4   5   56 3   row2    74  74  3   534 4   row3    865 768 8   7 5   row4    68  86  65  87 
  • I tried: colnames(t1) <- t1[1,]. Nothing happens.

  • I tried: names(t1) <- ti[1,], Nothing happens.

  • I tried: lapply(t1, function(x) {names(x) <- x[1, ]; x}). It returns an error message:

    Error in `[.default`(x, 1, ) : incorrect number of dimensions 

Could anyone help?

like image 386
sstww Avatar asked Aug 17 '15 15:08

sstww


People also ask

How do I make column names a row in R?

The rownames() method in R is used to assign row names to the dataframe. It is assigned using a character vector consisting of desired names with a length equivalent to the number of rows in dataframe. We can simply assign it to any column of the dataframe if it contains all unique values.

How do I assign a column name in R?

Method 1: using colnames() method colnames() method in R is used to rename and replace the column names of the data frame in R. The columns of the data frame can be renamed by specifying the new column names as a vector. The new name replaces the corresponding old name of the column in the data frame.

How do I create a column header 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”,…..)


2 Answers

Sam Firke's ever useful package janitor has a function especially for this: row_to_names.

Example from his documentation:

library(janitor)  x <- data.frame(X_1 = c(NA, "Title", 1:3),            X_2 = c(NA, "Title2", 4:6)) x %>%   row_to_names(row_number = 2) 
like image 144
zek19 Avatar answered Sep 23 '22 12:09

zek19


header.true <- function(df) {   names(df) <- as.character(unlist(df[1,]))   df[-1,] } 

Test

df1 <- data.frame(c("a", 1,2,3), c("b", 4,5,6)) header.true(df1)   a b 2 1 4 3 2 5 4 3 6 
like image 29
Pierre L Avatar answered Sep 26 '22 12:09

Pierre L