How can I add rows to an R data frame every other row?

a different ben picture a different ben · May 9, 2013 · Viewed 6.9k times · Source

Brief: how can I add m rows to my m X n data frame, where each new row is inserted after each existing row? I will essentially copy the existing row, but make a change to one variable.

More detail: in reference to another question, I think I can do what I want with rgl's segments3d function. I have a set of x,y,z points, but these are just one end point of a set of line segments. The other end point is so many metres away in the Z dimension, given as a fourth variable: X,Y,Z,Z_Length; in my terminology it's easting,northing,elevation,length.

According to the rgl docs, "Points are taken in pairs by segments3d". So, I think I need to modify my data frame to have extra entries every second line with an altered Z variable (by subtracting Z_Length from Z). Visually, it needs to go from this:

+-------+---------+----------+-----------+---------+
| Label | easting | northing | elevation | length  |
+-------+---------+----------+-----------+---------+
| 47063 |  554952 |  5804714 | 32.68     | 619.25  |
| 47311 |  492126 |  5730703 | 10.40     | 1773.00 |
+-------+---------+----------+-----------+---------+

to this:

+-------+---------+----------+-----------+---------+
| Label | easting | northing | elevation | length  |
+-------+---------+----------+-----------+---------+
| 47063 |  554952 |  5804714 | 32.68     | 619.25  |
| 47063 |  554952 |  5804714 | -586.57   | 619.25  |
| 47311 |  492126 |  5730703 | 10.40     | 1773.00 |
| 47311 |  492126 |  5730703 | -1762.26  | 1773.00 |
+-------+---------+----------+-----------+---------+

A data sample at the linked question is available.

Answer

flodel picture flodel · May 9, 2013

Your sample data:

orig.df <- read.table(text = "
Label easting northing elevation length
47063  554952  5804714 32.68 619.25 
47311  492126  5730703 10.40 1773.00", header = TRUE)

Create your data to be inserted:

insert.df <- transform(orig.df, elevation = elevation - length)

Append it to your original data:

out.df <- rbind(orig.df, insert.df)

Reorder the rows:

n <- nrow(orig.df)
out.df[kronecker(1:n, c(0, n), "+"), ]
#   Label easting northing elevation  length
# 1 47063  554952  5804714     32.68  619.25
# 3 47063  554952  5804714   -586.57  619.25
# 2 47311  492126  5730703     10.40 1773.00
# 4 47311  492126  5730703  -1762.60 1773.00