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

前端 未结 5 1560
情书的邮戳
情书的邮戳 2020-12-19 07:49

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 ro

5条回答
  •  南笙
    南笙 (楼主)
    2020-12-19 08:30

    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
    

提交回复
热议问题