很多问题涉及重复观察的主题,但到目前为止,它们都没有对我有效。
在this questions中,我学会了如何从矢量中选择所有重复项。
# vector
id <- c("a","b","b","c","c","c","d","d","d","d")
#To return ALL duplicated values by specifying fromLast argument:
id[duplicated(id) | duplicated(id, fromLast=TRUE)]
## [1] "b" "b" "c" "c" "c" "d" "d" "d" "d"
#Yet another way to return ALL duplicated values, using %in% operator:
id[id %in% unique(id[duplicated(id)])]
## [1] "b" "b" "c" "c" "c" "d" "d" "d" "d"
现在有一个像这样的数据框:
dat <- data.frame(x = c(1, 1, 2, 2, 3),
y = c(5, 5, 6, 7, 8),
z = c('a', 'b', 'c', 'd', 'e'))
我如何选择同时具有x和y重复值的所有观测值,而不考虑z?
答案 0 :(得分:4)
你可以这样使用data.table
:
library(data.table)
setDT(dat)
# selects all (x,y) pairs that occur more than once
dat[ , if (.N > 1L) .SD, by = .(x, y)]
答案 1 :(得分:4)
使用dplyr
library(dplyr)
dat %>% group_by(x,y) %>% filter(n()>1)
# A tibble: 2 x 3
# x y z
# <dbl> <dbl> <fctr>
#1 1 5 a
#2 1 5 b
答案 2 :(得分:2)
在基地R
dat[ave(paste(dat$x,dat$y),dat$y,FUN=function(x) length(x))>1,]
x y z
1 1 5 a
2 1 5 b