[英]R - distinct value columns by group dplyr
我有以下 DataFrame,(這只是前 10 行)。
date_fichier pitd pce frequence date_debut segment profil car b1 b2 b3 s1 s2 s3
<dbl> <chr> <chr> <chr> <chr> <chr> <chr> <dbl> <dbl> <dbl> <dbl> <dbl> <dbl> <dbl>
1 201901030315 GD0991 0110~ 1M 2019-01-02 RES P012 9253 2 2 1 5.72e6 5.72e6 5.54e6
2 201901030315 GD0991 0115~ 1M 2019-01-02 RES P011 419 1 1 1 8.02e3 8.02e3 1.90e5
3 201901030315 GD0991 0117~ 6M 2019-01-02 RES P012 12226 2 2 1 5.72e6 5.72e6 5.54e6
4 201901030315 GD0991 0119~ 6M 2019-01-02 RES P012 11912 2 2 1 5.72e6 5.72e6 5.54e6
5 201901030315 GD0991 0121~ 1M 2019-01-02 RES P012 15378 2 2 1 5.72e6 5.72e6 5.54e6
6 201901030315 GD0991 0121~ 6M 2019-01-02 NRES P012 42220 2 2 1 5.72e6 5.72e6 5.54e6
7 201901030315 GD1007 0126~ 6M 2019-01-02 RES P012 6326 1 1 1 2.48e5 2.48e5 5.54e6
8 201901030315 GD0991 0127~ 1M 2019-01-02 RES P011 21 1 1 1 8.02e3 8.02e3 1.90e5
9 201901030315 GD0991 0129~ 1M 2019-01-02 RES P012 9645 2 2 1 5.72e6 5.72e6 5.54e6
10 201901030315 GD0991 0129~ 6M 2019-01-02 RES P012 10673 2 2 1 5.72e6 5.72e6 5.54e6
我的個人資料欄的范圍從 P011 到 P019。 每個配置文件的 b1、b2、b3 列范圍從 1 到 7。 這意味着 P011 的 b1 范圍為 1 到 7,b2 和 b3 的范圍也為 1 到 7。其他配置文件也具有相同的 b1、b2 和 b3 范圍。
正如您在上面的頭部看到的示例,第 1、3、4、5、6 行的輪廓為 P012,但它們的 b1 相同,它們的 b1 均為 2。
我想要一個 DataFrame,對於每個配置文件,我都會得到一個不同的 b1、b2 和 b3。
我試過:
f %>%
group_by(profil) %>%
distinct(b1, b2, b3, .keep_all =T) %>%
ungroup() %>%
dplyr::select(profil, b1, b2, b3 , s1, s2, s3) %>%
arrange(profil)
profil b1 b2 b3 s1 s2 s3
<chr> <dbl> <dbl> <dbl> <dbl> <dbl> <dbl>
1 P011 1 1 1 8018 8018 189985
2 P011 2 2 1 181967 181967 189985
3 P012 2 2 1 5715390 5715390 5544269
4 P012 1 1 1 247879 247879 5544269
5 P012 2 2 2 5715390 5715390 419000
但是正如您所看到的,我在第 1 行和第 2 行中為 P011 得到了相同的 b3。
我希望有:
profil b1 b2 b3
<chr> <dbl> <dbl> <dbl>
1 P011 1 1 1
2 P011 2 2 2
3 P012 1 1 1
5 P012 2 2 2
我怎樣才能做到這一點?
這是一個很好的第一次嘗試。 我的猜測是你在濫用distinct
。 我發現使用它的最簡單方法是distinct(dataframe)
返回 dataframe 中所有不同的行。
這為您提供了以下方法:
f %>%
select(profil, b1, b2, b3) %>%
distinct() %>%
arrange(profil, b1, b2, b3)
或者,假設您想要對所有重復項進行計數,或者獲取 profil、b1、b2 和 b3 的每個組合的最大 s1 值。 那么您的代碼將如下所示:
f %>%
group_by(profil, b1, b2, b3) %>%
summarise(count = n(),
largest_s1 = max(s1),
.groups = "drop") %>% # equivalent to upgroup
arrange(profil, b1, b2, b3)
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.