我有这个数据框:
A = data.frame(a = c("q", "e", "f", "q"), b = 1:4)
我想要获得2行(a中的重复q,具有不同的值,b中的1,4)
答案 0 :(得分:1)
我想你想要函数duplicated
:
A[A$a %in% A$a[duplicated(A$a)],]
# a b
# 1 q 1
# 4 q 4
这将为您提供包含在data.frame中找到2次或更多次的值的任何行。
@Sotos提出了这个问题,它在100.000行上的速度提高了20%:
A[duplicated(A$a)|duplicated(A$a, fromLast = TRUE),]
@ mohamed-nidabdella用dplyr提出了这个解决方案,速度提高了2.5倍:
A %>% group_by(a) %>% filter(n()>1)
基准:
A = data.frame(a =sample(letters,100000,replace=TRUE), b = 1:100000)
library(microbenchmark)
microbenchmark(
a = A[A$a %in% A$a[duplicated(A$a)],],
b =A[duplicated(A$a)|duplicated(A$a, fromLast = TRUE),],
c = A[A$a %in% unique(A$a[duplicated(A$a)]),],
d = A %>% group_by(a) %>% filter(n()>1),
times=100)
# Unit: milliseconds
# expr min lq mean median uq max neval
# a 23.549739 24.732701 27.71688 27.70747 28.463392 115.58251 100
# b 20.703155 21.485692 24.66477 21.79380 24.790283 113.42992 100
# c 23.215580 24.166518 26.83627 24.99078 27.824526 113.99780 100
# d 8.647365 9.099141 10.17412 9.25546 9.548462 46.96581 100
答案 1 :(得分:0)
library("data.table")
setDT(A)
rbind(A, A[a == "q", .(a, b = c(1, 4))])
# a b
# 1: q 1
# 2: e 2
# 3: f 3
# 4: q 4
# 5: q 1
# 6: q 4