类似于this问题,但在R中。Full-Join在某些情况下会添加重复值,即一个表在“ by”列中具有重复值,而另一个表则没有。
> df1 = data.frame(A=c(1,2,2,3), B=letters[1:4])
> df2 = data.frame(A=c(2,3,3,3), C=LETTERS[1:4])
> full_join(df1, df2, by="A") %>% arrange(A) %>% select(A,B,C)
A B C
1 1 a <NA>
2 2 b A
3 2 c A
4 3 d B
5 3 d C
6 3 d D
这是一个令人讨厌的应用程序。我有两个分类帐,按日期进行交易。每个帐户都有多个交易的日期。如果我尝试合并分类帐,它们将被彻底弄乱。
acct1 = data.frame(
Date=as.Date(c("2019/1/1", "2019/1/2", "2019/1/2", "2019/1/3")),
Amount=c(10, -20, -1, 25)
)
acct1
#> Date Amount
#> 1 2019-01-01 10
#> 2 2019-01-02 -20
#> 3 2019-01-02 -1
#> 4 2019-01-03 25
acct2 = data.frame(
Date=as.Date(c("2019/1/2", "2019/1/3", "2019/1/3", "2019/1/3")),
Amount=c(7, 0, -7, 0)
)
acct2
#> Date Amount
#> 1 2019-01-02 7
#> 2 2019-01-03 0
#> 3 2019-01-03 -7
#> 4 2019-01-03 0
dplyr::full_join(acct1, acct2, by="Date", suffix=c(".ACCT1", ".ACCT2"))
#> Date Amount.ACCT1 Amount.ACCT2
#> 1 2019-01-01 10 NA
#> 2 2019-01-02 -20 7
#> 3 2019-01-02 -1 7
#> 4 2019-01-03 25 0
#> 5 2019-01-03 25 -7
#> 6 2019-01-03 25 0
由reprex package(v0.3.0)于2019-06-17创建
我刚刚发现了this个问题,可能有解决方案。
工程
acct1 = data.frame(
Date=as.Date(c("2019/1/1", "2019/1/2", "2019/1/2", "2019/1/3")),
Amount=c(10, -20, -1, 25)
)
acct1 = acct1 %>% mutate(rownum=row_number())
#> Error in acct1 %>% mutate(rownum = row_number()): could not find function "%>%"
acct1
#> Date Amount
#> 1 2019-01-01 10
#> 2 2019-01-02 -20
#> 3 2019-01-02 -1
#> 4 2019-01-03 25
acct2 = data.frame(
Date=as.Date(c("2019/1/2", "2019/1/3", "2019/1/3", "2019/1/3")),
Amount=c(7, 0, -7, 0)
)
acct2 = acct2 %>% mutate(rownum=row_number())
#> Error in acct2 %>% mutate(rownum = row_number()): could not find function "%>%"
acct2
#> Date Amount
#> 1 2019-01-02 7
#> 2 2019-01-03 0
#> 3 2019-01-03 -7
#> 4 2019-01-03 0
dplyr::full_join(acct1, acct2, by=c("rownum", "Date"), suffix=c(".ACCT1", ".ACCT2")) %>%
select(-rownum) %>%
arrange(Date)
#> Date Amount.ACCT1 Amount.ACCT2
#> 1 2019-01-01 10 NA
#> 2 2019-01-02 -20 NA
#> 3 2019-01-02 -1 NA
#> 4 2019-01-02 NA 7
#> 5 2019-01-03 25 0
#> 6 2019-01-03 NA 0
#> 7 2019-01-03 NA -7
由reprex package(v0.3.0)于2019-06-17创建
答案 0 :(得分:1)
根据我先前在OP中引用的non-SO answer进行调整:
full_join(acct1 %>% group_by(Date) %>% mutate(id = row_number()),
acct2 %>% group_by(Date) %>% mutate(id = row_number()),
by = c("id", "Date")) %>%
arrange(Date) %>%
ungroup() %>%
select(Date, id, acct1 = Amount.x, acct2 = Amount.y)
# A tibble: 6 x 4
Date id acct1 acct2
<date> <int> <dbl> <dbl>
1 2019-01-01 1 10 NA
2 2019-01-02 1 -20 7
3 2019-01-02 2 -1 NA
4 2019-01-03 1 25 0
5 2019-01-03 2 NA -7
6 2019-01-03 3 NA 0
答案 1 :(得分:0)
由于每天可以进行1笔以上的交易,因此列表比引导更为自然。示例:
acct1 <- acct1 %>% group_by(Date) %>% summarize(Amount = list(Amount))
acct2 <- acct2 %>% group_by(Date) %>% summarize(Amount = list(Amount))
dplyr::full_join(acct1, acct2, by="Date", suffix=c(".ACCT1", ".ACCT2")) %>% as.data.frame
Date Amount.ACCT1 Amount.ACCT2
1 2019-01-01 10 NULL
2 2019-01-02 -20, -1 7
3 2019-01-03 25 0, -7, 0
使用这种方法,您不会得到重复的交易。