Reputation: 13
I have a data frame that looks kind of like this:
#1 sampleid replication measurement
#2 1 1 0.5
#3 1 2 0.4
#4 1 3 0.3
#5 1 4 0.2
#6 1 5 0.3
#7 2 1 0.5
#8 3 1 0.5
#9 4 1 0.5
#10 4 2 0.3
#11 4 3 0.2
#12 5 1 0.1
This is my second day with R so I'm sorry if this is a rather simple task.
What I would like to do is exclude "measurement" and "sampleid" if the corresponding "replication" is <2. Based on the sample I gave, I'd like to see exclusions in lines #7, #8, and #12.
I tried using a combination of subset
and length
, but it didn't achieve what I needed. Is there a simple way that I'm missing?
Thanks a lot.
Upvotes: 1
Views: 247
Reputation: 887048
An option using dplyr
is
library(dplyr)
dat %>%
group_by(sampleid) %>%
filter(n() > 1)
# sampleid replication measurement
# <int> <int> <dbl>
#1 1 1 0.5
#2 1 2 0.4
#3 1 3 0.3
#4 1 4 0.2
#5 1 5 0.3
#6 4 1 0.5
#7 4 2 0.3
#8 4 3 0.2
Upvotes: 0
Reputation: 73265
We can use ave
:
subset(dat, ave(replication, sampleid, FUN = length) >= 2)
# sampleid replication measurement
#1 1 1 0.5
#2 1 2 0.4
#3 1 3 0.3
#4 1 4 0.2
#5 1 5 0.3
#8 4 1 0.5
#9 4 2 0.3
#10 4 3 0.2
Data:
dat <- structure(list(sampleid = c(1L, 1L, 1L, 1L, 1L, 2L, 3L, 4L, 4L,
4L, 5L), replication = c(1L, 2L, 3L, 4L, 5L, 1L, 1L, 1L, 2L,
3L, 1L), measurement = c(0.5, 0.4, 0.3, 0.2, 0.3, 0.5, 0.5, 0.5,
0.3, 0.2, 0.1)), .Names = c("sampleid", "replication", "measurement"
), class = "data.frame", row.names = c(NA, -11L))
Upvotes: 2
Reputation: 659
subset(data, sampleid %in% unique(data$sampleid[duplicated(data$sampleid)]))
Upvotes: 0