0 votes
1 view
in R Programming by (6.5k 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 (25.3k points)

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

Welcome to Intellipaat Community. Get your technical queries answered by top developers !


Categories

...