Intellipaat Back

Explore Courses Blog Tutorials Interview Questions
0 votes
2 views
in R Programming by (7.3k points)

The following code combines a vector with a data frame:

newrow = c(1:4)

existingDF = rbind(existingDF,newrow)

However, this code always inserts the new row at the end of the data frame.

How can I insert the row at a specified point within the data frame? For example, let's say the data frame has 20 rows, how can I insert the new row between rows 10 and 11?

1 Answer

0 votes
by

To insert a row at a specific index in a data frame, use the rbind() function as follows:

df <- as.data.frame(matrix(seq(110),nrow=11,ncol=5))

rindex <- 10

newrow <- seq(1,5)

To insert the new row:

df <- rbind(df[1:rindex,],newrow,df[-(1:rindex),])

df

Output:

    V1 V2 V3 V4 V5

1    1 12 23 34 45

2    2 13 24 35 46

3    3 14 25 36 47

4    4 15 26 37 48

5    5 16 27 38 49

6    6 17 28 39 50

7    7 18 29 40 51

8    8 19 30 41 52

9    9 20 31 42 53

10  10 21 32 43 54

11   1  2  3  4  5

111 11 22 33 44 55

A new row is inserted between 10th and 11th row.

Related questions

31k questions

32.8k answers

501 comments

693 users

Browse Categories

...