[英]Combine two datasets covering all the possible combinations
我在執行連接操作時遇到問題。
我的兩個數據框是:
library(tidiverse)
df_one <- data.frame(
cohort = c("2019-03-01", "2019-03-01", "2019-03-01", "2019-04-01",
"2019-04-01", "2019-05-01"),
periods = c(1, 2, 3, 1, 2, 1),
value = c(13, 24, 35, 22, 38, 21)
)
df_two <- data.frame(
periods = c(1, 2, 3, 4),
value_2 = c(100, 73, 45, 29)
)
我想要實現的最終結果是一個加入的 dataframe 包含 df_two 中的所有可能組合 - 對df_two
中的元素df_one
- 如下:
df_final <- data.frame(
cohort = c("2019-03-01", "2019-03-01", "2019-03-01", "2019-03-01",
"2019-04-01", "2019-04-01", "2019-04-01",
"2019-04-01", "2019-05-01", "2019-05-01", "2019-05-01",
"2019-05-01"),
periods = c(1, 2, 3, 4, 1, 2, 3, 4, 1, 2, 3, 4),
value = c(13, 24, 35, NA, 22, 38, NA, NA, 21, NA, NA, NA),
value_2 = c(100, 73, 45, 29, 100, 73, 45, 29, 100, 73, 45, 29)
)
cohort periods value value_2
1 2019-03-01 1 13 100
2 2019-03-01 2 24 73
3 2019-03-01 3 35 45
4 2019-03-01 4 NA 29
5 2019-04-01 1 22 100
6 2019-04-01 2 38 73
7 2019-04-01 3 NA 45
8 2019-04-01 4 NA 29
9 2019-05-01 1 21 100
10 2019-05-01 2 NA 73
11 2019-05-01 3 NA 45
12 2019-05-01 4 NA 29
我嘗試使用crossing()
:
crossing(df_one, df_two)
但我得到了錯誤:
Error: Column name `periods` must not be duplicated.
Run `rlang::last_error()` to see where the error occurred.
一旦修復了唯一列名 - 正如用戶 @akrun 所建議的那樣 - 通過:
crossing(df_one, df_two, .name_repair = "unique")
我意識到crossing()
不會產生我想要的結果。
我應該遵循什么方法來獲得df_final
?
crossing
需要唯一的列名,“句點”是重復的。 根據?crossing
穿越(...,.name_repair =“check_unique”)
這意味着默認選項將檢查唯一的列名,如果有重復,它將引發錯誤。
library(dplyr)
library(tidyr)
library(stringr)
我們可以更改.name_repair
以強制列名“唯一”
crossing(df_one, df_two, .name_repair = "unique")
#New names:
#* periods -> periods...2
#* periods -> periods...4
# A tibble: 24 x 5
# cohort periods...2 value periods...4 value_2
# <chr> <dbl> <dbl> <dbl> <dbl>
# 1 2019-03-01 1 13 1 100
# 2 2019-03-01 1 13 2 73
# 3 2019-03-01 1 13 3 45
# 4 2019-03-01 1 13 4 29
# 5 2019-03-01 2 24 1 100
# 6 2019-03-01 2 24 2 73
# 7 2019-03-01 2 24 3 45
# 8 2019-03-01 2 24 4 29
# 9 2019-03-01 3 35 1 100
#10 2019-03-01 3 35 2 73
# … with 14 more rows
或者使用“最小”,其中將保留重復的列名(但從長遠來看,這會使事情變得更加復雜
為了達到預期,我們可以在第一個數據集上complete
分組,然后在第二個數據集上使用left_join
df_one %>%
group_by(cohort) %>%
complete(periods = df_two$periods) %>%
left_join(df_two)
# A tibble: 12 x 4
# Groups: cohort [3]
# cohort periods value value_2
# <chr> <dbl> <dbl> <dbl>
# 1 2019-03-01 1 13 100
# 2 2019-03-01 2 24 73
# 3 2019-03-01 3 35 45
# 4 2019-03-01 4 NA 29
# 5 2019-04-01 1 22 100
# 6 2019-04-01 2 38 73
# 7 2019-04-01 3 NA 45
# 8 2019-04-01 4 NA 29
# 9 2019-05-01 1 21 100
#10 2019-05-01 2 NA 73
#11 2019-05-01 3 NA 45
#12 2019-05-01 4 NA 29
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.