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

其他回答

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

使用底数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))

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

删除完全相同的行:

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

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

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

dplyr包中的distinct()函数执行任意重复删除,可以从特定列/变量中删除(如本问题中所示),也可以考虑所有列/变量。Dplyr是潮汐宇宙的一部分。

数据和包装

library(dplyr)
dat <- data.frame(a = rep(c(1,2),4), b = rep(LETTERS[1:4],2))

删除在特定列中重复的行(例如,columna)

注意.keep_all = TRUE保留所有列,否则只保留列a。

distinct(dat, a, .keep_all = TRUE)

  a b
1 1 A
2 2 B

删除与其他行完全重复的行:

distinct(dat)

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

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

删除数据帧的重复行

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