簡體   English   中英

如何只保留唯一的行卻忽略列?

[英]How to keep only unique rows but ignore a column?

如果我有此數據:

df1 <- data.frame(name = c("apple", "apple", "apple", "orange", "orange"),
       ID = c(1, 2, 3, 4, 5),
       is_fruit = c("yes", "yes", "yes", "yes", "yes"))

並且我只想保留唯一的行,但是忽略ID列,以使輸出看起來像這樣:

df2 <- data.frame(name = c("apple", "orange"),
       ID = c(1, 4),
       is_fruit = c("yes", "yes"))

df2
#    name ID is_fruit
#1  apple  1      yes
#2 orange  4      yes

我最好怎么用dplyr做到這dplyr

您可以使用distinct功能; 通過顯式指定變量,您可以僅基於這些列保留唯一的行; 也來自?distinct

如果給定的輸入組合有多個行,則僅保留第一行

distinct(df1, name, is_fruit, .keep_all = T)
#    name ID is_fruit
#1  apple  1      yes
#2 orange  4      yes

基數R

df1[!duplicated(df1[!names(df1) %in% c("ID")]),]
#    name ID is_fruit
#1  apple  1      yes
#4 orange  4      yes

c("ID")替換為要忽略的列的名稱

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM