我读了一个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

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


当前回答

只需要将你的数据帧与你需要的列隔离,然后使用唯一的函数: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.

其他回答

删除数据帧的重复行

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/)

sqldf:

# Example by Mehdi Nellen
a <- c(rep("A", 3), rep("B", 3), rep("C",2))
b <- c(1,1,2,4,1,1,2,2)
df <-data.frame(a,b)

解决方案:

 library(sqldf)
    sqldf('SELECT DISTINCT * FROM df')

输出:

  a b
1 A 1
2 A 2
3 B 4
4 B 1
5 C 2

对于那些来这里寻找重复行删除的一般答案的人,请使用!duplicate ():

a <- c(rep("A", 3), rep("B", 3), rep("C",2))
b <- c(1,1,2,4,1,1,2,2)
df <-data.frame(a,b)

duplicated(df)
[1] FALSE  TRUE FALSE FALSE FALSE  TRUE FALSE  TRUE

> df[duplicated(df), ]
  a b
2 A 1
6 B 1
8 C 2

> df[!duplicated(df), ]
  a b
1 A 1
3 A 2
4 B 4
5 B 1
7 C 2

回答:从R数据帧中删除重复的行

默认情况下,该方法将保留每个副本的第一次出现。您可以使用fromLast = TRUE参数来保留每个重复项的最后一次出现。在此步骤之前,您可以对数据进行排序,以便保留所需的行。

这个问题也可以通过从每个组中选择第一行来解决,其中组是我们想要选择唯一值的列(在共享的示例中,它只是第一列)。

使用底数R:

subset(df, ave(V2, V1, FUN = seq_along) == 1)

#                      V1  V2 V3     V4 V5
#1 platform_external_dbus 202 16 google  1

在dplyr

library(dplyr)
df %>% group_by(V1) %>% slice(1L)

或者使用data.table

library(data.table)
setDT(df)[, .SD[1L], by = V1]

如果我们需要根据多个列找出唯一的行,只需在分组部分为上面的每个答案添加这些列名。

data

df <- structure(list(V1 = structure(c(1L, 1L, 1L, 1L, 1L), 
.Label = "platform_external_dbus", class = "factor"), 
V2 = c(202L, 202L, 202L, 202L, 202L), V3 = c(16L, 16L, 16L, 
16L, 16L), V4 = structure(c(1L, 4L, 3L, 5L, 2L), .Label = c("google", 
"hughsie", "localhost", "space-ghost.verbum", "users.sourceforge"
), class = "factor"), V5 = c(1L, 1L, 1L, 8L, 1L)), class = "data.frame", 
row.names = c(NA, -5L))

一般的答案可以是 例如:

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