Append to Data Frame in Loop in R (2 Examples) | Add Column / Row in for-Loop

 

In this tutorial you’ll learn how to add new columns and rows within loops in the R programming language.

Table of contents:

Let’s get started!

 

Creation of Example Data

As a first step, we’ll have to define some data that we can use in the examples below:

data <- data.frame(x1 = 1:5,                      # Create example data
                   x2 = 6:10,
                   x3 = 11:15)
data                                              # Return example data
#   x1 x2 x3
# 1  1  6 11
# 2  2  7 12
# 3  3  8 13
# 4  4  9 14
# 5  5 10 15

Have a look at the previous output of the RStudio console. It shows that our example data frame consists of five rows and three columns.

 

Example 1: Add New Column to Data Frame in for-Loop

In Example 1, I’ll show how to append a new variable to a data frame in a for-loop in R. Have a look at the following R code:

for(i in 1:3) {                                   # Head of for-loop
  new <- rep(i, nrow(data))                       # Create new column
  data[ , ncol(data) + 1] <- new                  # Append new column
  colnames(data)[ncol(data)] <- paste0("new", i)  # Rename column name
}

Within the for-loop we have performed three steps: First, we have created a vector object containing the values that we wanted to add as column to our data frame. Second, we added the new column ad the end of our data frame. Third, we renamed our new column (this step is optional).

Let’s have a look at the final output:

data                                              # Return updated data
#   x1 x2 x3 new1 new2 new3
# 1  1  6 11    1    2    3
# 2  2  7 12    1    2    3
# 3  3  8 13    1    2    3
# 4  4  9 14    1    2    3
# 5  5 10 15    1    2    3

As you can see based on the previous output of the RStudio console, we added three new variables to our data matrix.

 

Example 2: Add New Row to Data Frame in for-Loop

In this Example, I’ll explain how to append new rows to a data frame in a for-loop in R. Similar to Example 1, we have to create a vector object that we want to add as new row and we have to append this vector at the bottom of our data frame:

for(i in 1:2) {                                   # Head of for-loop
  new <- rep(i, ncol(data))                       # Create new row
  data[nrow(data) + 1, ] <- new                   # Append new row
}

As you can see in the following output, we have appended two new rows to our data table:

data                                              # Return updated data
#   x1 x2 x3 new1 new2 new3
# 1  1  6 11    1    2    3
# 2  2  7 12    1    2    3
# 3  3  8 13    1    2    3
# 4  4  9 14    1    2    3
# 5  5 10 15    1    2    3
# 6  1  1  1    1    1    1
# 7  2  2  2    2    2    2

Now that we could apply the same logic if we want to append a new column or row to a data frame within a while-loop or a repeat-loop.

 

Video & Further Resources

Do you need more explanations on the R code of this tutorial? Then you might watch the following video of my YouTube channel. I show the contents of this tutorial in the video:

 

 

In addition, you might read the other posts which I have published on this website. I have released numerous articles already.

 

In this tutorial you learned how to append a new variable or row to a data frame in the R programming language. In case you have further questions, don’t hesitate to tell me about it in the comments section below.

 

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.


2 Comments. Leave new

  • Growing data.frames in a for-loop is not a good practise because it induces copy-on-modify (https://adv-r.hadley.nz/names-values.html#copy-on-modify) and shouldn’t actually be used (https://adv-r.hadley.nz/perf-improve.html#avoid-copies)

    Reply
    • Hello Frederik,

      Thank you for your input. It is nice to have such readers like you. It is great to see our readers connect with the community and share tips with others. We select our topics based on user demand and try to provide as many alternatives as possible through different tutorials. In general, using apply() functions can be more memory efficient than using loops in R, especially when working with larger datasets. We advise our readers to check our tutorials: Avoid for-Loop and apply() Functions. It’s also worth noting that while apply() functions can improve memory efficiency, they may not always be the best choice for every situation. Other functions, such as those provided by the dplyr and data.table packages can often provide more efficient and readable solutions for data manipulation tasks.

      Regards,
      Cansu

      Reply

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