将中间观测值添加到数据框(手动插值)

时间:2019-01-18 18:02:55

标签: r dataframe dplyr tidyverse purrr

我有一个如下所示的带有矢量坐标的数据框:

df <- structure(list(x0 = c(22.6, 38.5, 73.7), y0 = c(62.9, 56.6, 27.7
), x1 = c(45.8, 49.3, 80.8), y1 = c(69.9, 21.9, 14)), row.names = c(NA, 
-3L), class = c("tbl_df", "tbl", "data.frame"))
# A tibble: 3 x 4
     x0    y0    x1    y1
  <dbl> <dbl> <dbl> <dbl>
1  22.6  62.9  45.8  69.9
2  38.5  56.6  49.3  21.9
3  73.7  27.7  80.8  14 

出于可视化目的,我需要手动插入点,即在df的每两行之间添加一个中间行,其中起始坐标x0, y0是原始的前一行的结束坐标,而结束时坐标x1, y1是原始下一行的起始坐标。如果观察是来自原始数据集或手动添加的,我还需要保留信息。因此,预期输出为:

# A tibble: 5 x 5
      x     y pass_end_x pass_end_y source  
  <dbl> <dbl>      <dbl>      <dbl> <chr>   
1  22.6  62.9       45.8       69.9 original
2  45.8  69.9       38.5       56.6 added   
3  38.5  56.6       49.3       21.9 original
4  49.3  21.9       73.7       27.7 added   
5  73.7  27.7       80.8       14   original

我该如何高效且优雅地做到这一点(最好在tidyverse中使用)?

1 个答案:

答案 0 :(得分:0)

为此,我要做的就是交换起点和终点的列名,然后使用<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script> <div class="myclass">Foo</div>获取下一个值lead和{{1} }。然后,我们只需添加x1标签和y1

source

结果:

bind_rows

如果您需要按顺序排列行:

library(tidyverse)

df2 <- df

names(df2) <- names(df2)[c(3,4,1,2)] # swap names

df2 <- df2 %>% mutate(x1 = lead(x1), y1 = lead(y1),source = "added")

df <- df %>% mutate(source = "original") %>% bind_rows(., df2)