row as a header in R

Use data frame row as a column names in R

Here is how to use data frame row as a column names in R, or, in other words, convert the data frame row as a header in R.

Here is my data frame and the second row contains data frame column names.

df <- data.frame(
  stringsAsFactors = FALSE,
  Column1 = c("Height",
              "23", "73", "12"),
  Column2 = c("Width",
              "199", "312", "218")
)

df

#  Column1 Column2
#1  Height   Width
#2      23     199
#3      73     312
#4      12     218

Sometimes it is the result of data import, and if that is the case, look for a header argument. Usually, if the column names are in the second row, that is the case. Functions like read.table defaulting header argument to false.

 

move row to data frame header with the janitor

The fastest and easiest way to use data frame row as a column names is with row_to_names from the janitor package. Be careful with the remove_rows_above argument. By default, all the rows above are removed. In this situation, that is not a problem. Header values are in the first row.

janitor::row_to_names(df, 1, remove_rows_above = FALSE) 

#  Height Width
#2     23   199
#3     73   312
#4     12   218

 

use dplyr to replace column names with vector

With the help of function set_names from the purrr package, you can replace actual column names with the vector that is from the data frame row content.

require(dplyr)

df %>%
  purrr::set_names(as.character(slice(., 1))) %>%
  slice(-1)

#  Height Width
#1     23   199
#2     73   312
#3     12   218

If it is a small data frame, you can simply create a new header by dplyr.

 

use data frame row as column names in base R

No matter which row contains data frame column names, you can use relevant location. Firstly, take values from the necessary row and assign them to the data frame header.

names(df) <- df[1, ]
df

#  Height Width
#1 Height Width
#2     23   199
#3     73   312
#4     12   218

Secondly, remove that row.

df <- df[-1, ]
df

#  Height Width
#2     23   199
#3     73   312
#4     12   218

 

This is only one of the problems that might be necessary to solve in data with R.
Be prepared to deal with data wrangling with these dplyr tips and tricks, how to quickly drop unnecessary columns, replace values or remove unnecessary characters.





Posted

in

Comments

Leave a Reply

Your email address will not be published. Required fields are marked *