r - 在 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
解决方案
一种方法是将日期增加1 天,从indf
替换并绑定到原始数据框。Value
df2
df
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
推荐阅读
- python - python 如何处理对象名称和类定义?
- angular - Angular 和 Laravel 授权标头 CORS 错误
- javascript - JS:如何从中创建一个 for 循环?
- r - 按日期计算data.frame中所有点之间的距离
- c# - C#中的SQL注入
- javascript - Positioning style.left for DIV with javascript does not work
- apache-nifi - invokeHTTP 中“Put Response Body In Attribute”的属性名称
- apache-spark - 如何在 Spark Structured Streaming 中指定批处理间隔?
- system-verilog - 系统 Verilog:ref 类成员
- c# - 转换泛型类型以构建有效的 Linq 表达式