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

其他回答

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

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

删除数据帧的重复行

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

或者你可以用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()在任何位置返回到原始数据帧。

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