R 如何只保留唯一的行而忽略列?
如果我有这些数据:R 如何只保留唯一的行而忽略列?,r,dplyr,R,Dplyr,如果我有这些数据: 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")) 我如何做到这一点,理想情况下使用dplyr?您可以使用distinct函数;通过显式指定变量,您可以仅基于这些列保留唯一的行;以及来自?不同的: 如果
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"))
我如何做到这一点,理想情况下使用
dplyr
?您可以使用distinct
函数;通过显式指定变量,您可以仅基于这些列保留唯一的行;以及来自?不同的:
如果给定的输入组合有多行,则仅保留第一行
您可以使用distinct
功能;通过显式指定变量,您可以仅基于这些列保留唯一的行;以及来自?不同的:
如果给定的输入组合有多行,则仅保留第一行
基尔
用要忽略的列的名称替换c(“ID”)
df1[!duplicated(df1[!names(df1) %in% c("ID")]),]
# name ID is_fruit
#1 apple 1 yes
#4 orange 4 yes
将c(“ID”)
替换为要忽略的列的名称Base R:df1[!duplicated(df1[-2]),]
Base R:df1[!duplicated(df1[-2]),]
distinct(df1, name, is_fruit, .keep_all = T)
# name ID is_fruit
#1 apple 1 yes
#2 orange 4 yes
df1[!duplicated(df1[!names(df1) %in% c("ID")]),]
# name ID is_fruit
#1 apple 1 yes
#4 orange 4 yes