Do Not Lose Variable Names when Row is Added to Empty Data Frame in R (2 Examples)

In this R programming post you’ll learn how to retain the variable names when a new row is added to an empty data frame.

Introduction of Example Data

my_df <- data.frame(col_A = character(),    # Constructing an empty data frame
                    col_B = character(),
                    col_C = character(),
                    col_D = character())
my_df
# [1] col_A col_B col_C col_D
# <0 rows> (or 0-length row.names)
my_row <- LETTERS[1:4]                      # Constructing a new row
my_row
# [1] "A" "B" "C" "D"

Example 1: Lose Column Names when Adding Row to Empty Data Frame

df_new1 <- rbind(my_df, my_row)             # Using rbind() function
df_new1
#   X.A. X.B. X.C. X.D.
# 1    A    B    C    D

Example 2: Keep Column Names when Adding Row to Empty Data Frame

df_new2 <- my_df                            # Adding new row at certain index position
df_new2[nrow(df_new2) + 1, ] <- my_row
df_new2
#   col_A col_B col_C col_D
# 1     A     B     C     D

Related Articles & Further Resources

Have a look at the following R programming tutorials. They discuss similar topics as this page:

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.
You need to agree with the terms to proceed

Menu
Top