Add Row to R Data Frame

To add row to R Data Frame, append the list or vector representing the row, to the end of the data frame.

The syntax to add new row to data frame df is

</>
Copy
df[nrow(df) + 1,] <- new_row

nrow(df) returns the number of rows in data frame. nrow(df) + 1 means the next row after the end of data frame. Assign the new row to this row position in the data frame.

Examples

Add Row to Data Frame

In the following program, we create a data frame with four initial rows, and then add a new row (as fifth row).

Example.R

</>
Copy
#create data frame
df <- data.frame("c1" = c(41, 42, 43, 44),
                 "c2" = c(45, 46, 47, 48),
                 "c3" = c(49, 50, 51, 52))
#add row
df[nrow(df) + 1,] <- c(10, 20, 30)
#print
print(df)

Output

  c1 c2 c3
1 41 45 49
2 42 46 50
3 43 47 51
4 44 48 52
5 10 20 30

Add Rows to Empty Data Frame

Now, let us take an empty data frame with two columns, and add new rows to it.

Example.R

</>
Copy
#create data frame with two columns
df <- data.frame(matrix(ncol = 2, nrow = 0))
colnames(df) <-c("c1", "c2")
#add rows
df[1,] <- c(10, 20)
df[2,] <- c(30, 40)
df[3,] <- c(50, 60)
#print
print(df)

Output

  c1 c2
1 10 20
2 30 40
3 50 60

Conclusion

In this R Tutorial, we learned to add new rows to an R Data Frame using data frame indexing mechanism, with the help of examples.