Assign Column Names Based On Existing Row in R (2 Examples)

 

This tutorial illustrates how to convert the values in a row to the header of a data frame in R.

The page looks as follows:

Here’s how to do it:

 

Creation of Exemplifying Data

The following data will be used as basement for this R tutorial:

data <- data.frame(x1 = letters[1:5],    # Create example data
                   x2 = "x",
                   x3 = LETTERS[9:5])
data                                     # Print example data

 

table 1 data frame assign column names based on existing row r

 

As you can see based on Table 1, our example data is a data frame consisting of five rows and three columns.

 

Example 1: Convert First Row to Header of Data Frame

Example 1 illustrates how to use the first row of a data frame as variable names.

data_new <- data                         # Duplicate data frame
colnames(data_new) <- data[1, ]          # Convert first row to header
data_new                                 # Print updated data frame

 

table 2 data frame assign column names based on existing row r

 

After executing the previous R syntax the data frame revealed in Table 2 has been created. As you can see, the column names of this data frame are equal to the values of the first row.

 

Example 2: Remove Header Row from Data Frame

In Example 2, I’ll explain how to remove the row containing the values that we have used as header (i.e. the first row).

Have a look at the following R code:

data_new <- data_new[- 1, ]              # Remove first row of data
data_new                                 # Print updated data frame

 

table 3 data frame assign column names based on existing row r

 

By running the previous code we have created Table 3, i.e. our data frame without the first row.

 

Video, Further Resources & Summary

Would you like to learn more about column names? Then I recommend watching the following video of my YouTube channel. I’m explaining the R syntax of this tutorial in the video instruction:

 

 

Furthermore, you may read the related articles of my website. I have released numerous articles already.

 

This tutorial has illustrated how to use a row as column names in R programming. In case you have any additional questions, don’t hesitate to let me know in the comments.

 

Subscribe to the Statistics Globe Newsletter

Get regular updates on the latest tutorials, offers & news at Statistics Globe.
I hate spam & you may opt out anytime: Privacy Policy.


Leave a Reply

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

Fill out this field
Fill out this field
Please enter a valid email address.

Top