Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

dataframe

r

rgl

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.

like image 244
a different ben Avatar asked May 09 '13 02:05

a different ben


2 Answers

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
like image 171
flodel Avatar answered Sep 18 '22 20:09

flodel


I am not sure how rgl comes into play here, but if you just want to create a new data.frame with repeated values, try:

df[rep(1:nrow(df),1,each=2),]
like image 38
Nishanth Avatar answered Sep 16 '22 20:09

Nishanth