Avoid Losing Column Names when Adding Rows to Empty Data Frame in R (Example)
In this R article you’ll learn how to keep column names when a row is added to an empty data frame.
The article is structured as follows:
You’re here for the answer, so let’s get straight to the tutorial.
Creating Example Data
Consider the example data below:
data <- data.frame(x1 = numeric(), # Create empty data frame x2 = numeric(), x3 = numeric()) data # Print empty data frame # [1] x1 x2 x3 # <0 rows> (or 0-length row.names)
As you can see based on the previous output, our example data is a data frame containing zero rows and three variables called x1, x2, and x3.
Let’s also create a vector object containing the values for a new row:
new_row <- 1:3 # Create new row new_row # Print new row # [1] 1 2 3
Our vector contains the values 1, 2, and 3.
Example: Keep Column Names when Row-Binding Data
This example illustrates how to add a new row to an empty data frame without losing the column names of this data frame.
Let’s first illustrate in which case we are losing the column names:
data_lose <- rbind(data, new_row) # Lose column names data_lose # Print new data frame
The output of the previous R syntax is shown in Table 1 – A data frame containing the values of our new row, but different column names.
If we want to keep the column names of our empty data frame, we have to use the code below:
data_keep <- data # Duplicate data frame data_keep[nrow(data_keep) + 1, ] <- new_row # Keep column names data_keep # Print new data frame
By executing the previous R syntax, we have created Table 2, i.e. a new data frame with the values of our input vector and the column names of our input data frame.
Video, Further Resources & Summary
Do you need further info on data manipulation techniques and the R programming code of this tutorial? Then I can recommend watching the following video on my YouTube channel. I’m explaining the R code of this article in the video:
Please accept YouTube cookies to play this video. By accepting you will be accessing content from YouTube, a service provided by an external third party.
If you accept this notice, your choice will be saved and the page will refresh.
In addition, you may have a look at the other tutorials on my homepage:
- Specify Column Names for X & Y when Joining with dplyr Package
- Sort Variables of Data Frame by Column Names
- Set Column Names when Using cbind Function
- Convert Values in Column into Row Names of Data Frame
- Set Row & Column Names of Data with Unknown Dimension
- X. Prefix in Column Names when Reading Data Frame
- All R Programming Examples
You have learned in this tutorial how to retain the variable names when a new row is added to an empty data frame in R programming. If you have any further questions and/or comments, please let me know in the comments section.
Statistics Globe Newsletter