首页 > 解决方案 > 在 R 中的现有行之间添加新的数据行

问题描述

我有两个数据框,我想将它们连接在一起,以便在按降序对数据进行排序后,数据框df2在表的行之间移动df。我还想将日期添加到新添加的行中,以便每个日期都遵循日期的现有日期。

我的数据:

df
  Product       Date Value
1       A 2017-07-10    80
2       A 2017-07-01   150
3       B 2017-08-10    40
> df2
  Product  Month Value
1       A   July    90
2       A   July    50
3       B August    30

> result
  Product       Date Value
1       A 2017-07-01   150
2       A 2017-07-02    90
3       A 2017-07-10    80
4       A 2017-07-11    50
5       B 2017-08-10    40
6       B 2017-08-11    30


df <- data.frame(Product = c("A","A","B"),
                 Date = c("2017-07-10","2017-07-01","2017-08-10"),
                 Value =c(80,150,40))

df2 <- data.frame(Product = c("A","A","B"),
                 Month = c("July","July","August"),
                 Value =c(90,50,30))

不正确的解决方案:

df$Value[1] <- 500 ; df$Value[2] <- 50; df$Value[3] <- 400

Product       Date Value
1       A 2017-07-01    50
2       A 2017-07-02    90
3       A 2017-07-10   500
4       A 2017-07-11    50
5       B 2017-08-10   400
6       B 2017-08-11    30

Should be:

Product       Date Value
1       A 2017-07-01    50
2       A 2017-07-02    50
3       A 2017-07-10   500
4       A 2017-07-11    90
5       B 2017-08-10   400
6       B 2017-08-11    30

标签: rdataframemerge

解决方案


一种方法是将日期增加1 天,从indf替换并绑定到原始数​​据框。Valuedf2df

library(dplyr)  

df$Date <- as.Date(df$Date)

df %>%
  mutate(Date = Date + 1) %>%
  arrange(Product, Date) %>%
  mutate(Value = df2 %>% arrange(Product) %>%  pull(Value)) %>%
  bind_rows(df) %>%
  arrange(Product, Date)

#  Product       Date Value
#1       A 2017-07-01   150
#2       A 2017-07-02    90
#3       A 2017-07-10    80
#4       A 2017-07-11    50
#5       B 2017-08-10    40
#6       B 2017-08-11    30

推荐阅读