我读了一个CSV文件到R data.frame。有些行在其中一列中有相同的元素。我想删除该列中重复的行。例如:

platform_external_dbus          202           16                     google        1
platform_external_dbus          202           16         space-ghost.verbum        1
platform_external_dbus          202           16                  localhost        1
platform_external_dbus          202           16          users.sourceforge        8
platform_external_dbus          202           16                    hughsie        1

我只需要其中一行,因为其他的在第一列中有相同的数据。


当前回答

删除数据帧的重复行

library(dplyr)
mydata <- mtcars

# Remove duplicate rows of the dataframe
distinct(mydata)

在这个数据集中,没有一个重复的行,所以它返回与mydata中相同的行数。

基于一个变量删除重复行

library(dplyr)
mydata <- mtcars

# Remove duplicate rows of the dataframe using carb variable
distinct(mydata,carb, .keep_all= TRUE)

.keep_all函数用于保留输出数据帧中的所有其他变量。

基于多个变量删除重复行

library(dplyr)
mydata <- mtcars

# Remove duplicate rows of the dataframe using cyl and vs variables
distinct(mydata, cyl,vs, .keep_all= TRUE)

.keep_all函数用于保留输出数据帧中的所有其他变量。

(来源:http://www.datasciencemadesimple.com/remove-duplicate-rows-r-using-dplyr-distinct-function/)

其他回答

只需要将你的数据帧与你需要的列隔离,然后使用唯一的函数:D

# in the above example, you only need the first three columns
deduped.data <- unique( yourdata[ , 1:3 ] )
# the fourth column no longer 'distinguishes' them, 
# so they're duplicates and thrown out.

或者你可以用tidyr将cols 4和5中的数据嵌套到一行中:

library(tidyr)
df %>% nest(V4:V5)

# A tibble: 1 × 4
#                      V1    V2    V3             data
#                  <fctr> <int> <int>           <list>
#1 platform_external_dbus   202    16 <tibble [5 × 2]>

为了进行统计分析,现在删除了重复的col 2和3,但是将col 4和5数据保留在tibble中,并且可以使用unnest()在任何位置返回到原始数据帧。

一般的答案可以是 例如:

df <-  data.frame(rbind(c(2,9,6),c(4,6,7),c(4,6,7),c(4,6,7),c(2,9,6))))



new_df <- df[-which(duplicated(df)), ]

输出:

      X1 X2 X3
    1  2  9  6
    2  4  6  7

删除数据帧的重复行

library(dplyr)
mydata <- mtcars

# Remove duplicate rows of the dataframe
distinct(mydata)

在这个数据集中,没有一个重复的行,所以它返回与mydata中相同的行数。

基于一个变量删除重复行

library(dplyr)
mydata <- mtcars

# Remove duplicate rows of the dataframe using carb variable
distinct(mydata,carb, .keep_all= TRUE)

.keep_all函数用于保留输出数据帧中的所有其他变量。

基于多个变量删除重复行

library(dplyr)
mydata <- mtcars

# Remove duplicate rows of the dataframe using cyl and vs variables
distinct(mydata, cyl,vs, .keep_all= TRUE)

.keep_all函数用于保留输出数据帧中的所有其他变量。

(来源:http://www.datasciencemadesimple.com/remove-duplicate-rows-r-using-dplyr-distinct-function/)

这里有一个非常简单,快速的dplyr/整洁的解决方案:

删除完全相同的行:

library(dplyr)
iris %>% 
  distinct(.keep_all = TRUE)

删除仅在某些列中相同的行:

iris %>% 
  distinct(Sepal.Length, Sepal.Width, .keep_all = TRUE)