[R] How to get the duplicated elements from a vector?

Erik Iverson iverson at biostat.wisc.edu
Wed Oct 29 15:45:22 CET 2008



Leon Yee wrote:
 >
 > Gustaf Rydevik wrote:
 >> Hi Leon,
 >>
 >> unique(x)
 >>
 >> or
 >>
 >> duplicated(x)
 >>
 >> should work, depending on what you want.
 >>
 >> Best,
 >>
 >> Gustaf
 >>
 >
 > Hi,
 >    Thank you all. Actually, I have a data frame or matrix, whose first
 > column is numerical values, and whose 2nd column is names.

Then you have a data.frame, as matrices in R are of homogeneous type.

 >I need those
 > whose names repeated 3 times and get the mean of the 3 values for each
 > repeated names.
 >
 >    It sounds that I need some programming work.

Yes, but not much

## BEGIN R CODE
## guarantees there is at least one level with exactly three elements,
## which your problem seems to require
t1 <- data.frame(a = rnorm(10), b = c("D", "D", "D", 
sample(LETTERS[1:3], 7, replace = TRUE)))

## find which names have exactly three elements
t2 <- subset(t1, b %in% names(which(table(t1$b) == 3)))

## note that the elements of the returned value depend on what was
## originally in your data set's 'b' column
tapply(t2$a, t2$b, mean)

## END R CODE



 >
 > Regards,
 > Leon
 >
 > ______________________________________________
 > R-help at r-project.org mailing list
 > https://stat.ethz.ch/mailman/listinfo/r-help
 > PLEASE do read the posting guide
 > http://www.R-project.org/posting-guide.html
 > and provide commented, minimal, self-contained, reproducible code.



More information about the R-help mailing list