How to Create a Data Frame Row by Row in R (Example Code)

In this R tutorial you’ll learn how to create a data frame row by row.

Constructing Example Data

my_data <- data.frame(col1 = numeric(),    # Creating empty data
                      col2 = numeric(),
                      col3 = character(),
                      col4 = character(),
                      stringsAsFactors = FALSE)
my_data                                    # Showing data in RStudio console
# [1] col1 col2 col3 col4
# <0 rows> (or 0-length row.names)

Example: Using for-Loop and list() Function to Add New Rows to Data Frame

for(idx in 1:10) {                         # Starting for-loop
  list_one_row <- c(idx + 10,              # Constructing some data for one row
                    idx / 5,
                    letters[idx + 5],
                    "XXX")
  my_data[idx, ] <- list_one_row           # Appending values at tail of data frame
}
my_data                                    # Showing updated data in RStudio console
#    col1 col2 col3 col4
# 1    11  0.2    f  XXX
# 2    12  0.4    g  XXX
# 3    13  0.6    h  XXX
# 4    14  0.8    i  XXX
# 5    15    1    j  XXX
# 6    16  1.2    k  XXX
# 7    17  1.4    l  XXX
# 8    18  1.6    m  XXX
# 9    19  1.8    n  XXX
# 10   20    2    o  XXX

Further Resources

You may find some related R programming tutorials in the following list:

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