just_rookie just_rookie - 3 months ago 18
R Question

R append a new row to each row

I would like to insert a row into each beighboring rows, for example, the orginal data frame like this:

ID x y z value
1 1 1 1 2
2 4 7 9 3
3 9 2 5 8
4 8 6 1 4
5 7 3 5 9


And after inserting rows, the data frame should be like this:

ID x y z value
1 1 1 1 2
3 5 NA NA NA
2 4 7 9 3
8 1 NA NA NA
3 9 2 5 8
6 3 NA NA NA
4 8 6 1 4
9 7 NA NA NA
5 7 3 5 9
10 8 NA NA NA


I get two options, the first is appending new row to each row directly, and the second is add two columns to the dataframe, and then split a row into two rows.
So how to deal with this situation? Thank you in advance!

Answer

I am unable to understand where you are getting the data that you wish to insert into the data frame. So, I made a dummy set data2. Please refer code below, should work for what you need.

data <- read.table(text= "ID x y z value
                   1  1 1 1 2
                   2  4 7 9 3
                   3  9 2 5 8
                   4  8 6 1 4
                   5  7 3 5 9", header=T)

data2 <- data.frame(matrix(rnorm(2*nrow(data)),nrow(data)))
names(data2) <- names(data)[1:ncol(data2)]

combined <- plyr::rbind.fill(data,data2)
n <- nrow(data)
combined[kronecker(1:n, c(0, n), "+"),]
Comments