Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
719 views
in Technique[技术] by (71.8m points)

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

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.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

1.4m articles

1.4m replys

5 comments

57.0k users

...