Search code examples
rdplyrnarbind

Adding multiple NA rows to a data frame


I wanted to calculate something using a loop. The loop should go more than the number of my observations. For this reason, I want to first add NA rows to my data frame. Let's say my data frame is mtcars data. How can I add 10 NA rows in the mtcars data? The add_row()function from dplyr helps me to add only one NA row. Using rbind() also didn't help to add multiple rows.I probably need to loop this one too. But maybe there is an easy solution.


Solution

  • To add several rows of NA to the dataframe, you can try this:

    n <- 2 # Number of NA rows
    rbind(df, matrix(NA, nrow = n, ncol = NCOL(df), 
                     dimnames = list(NULL, colnames(df))))