Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

R Counting duplicate values and adding them to separate vectors [duplicate]

Tags:

r

x <- c(1,1,1,2,3,3,4,4,4,5,6,6,6,6,6,7,7,8,8,8,8)
y <- c('A','A','C','A','B','B','A','C','C','B','A','A','C','C','B','A','C','A','A','A','B')
X <- data.frame(x,y)

Above I have a data frame where I want to identify the duplicates in vector x, while counting the number of duplicate instances for both (x,y).... For example I have found that ddply and this post here is similar to what I am looking for (Find how many times duplicated rows repeat in R data frame).

library(ddply)
ddply(X,.(x,y), nrow)

This counts the number of instances 1 - A occurs which is 2 times... However I am looking for R to return the unique identifier in vector x with the counted number of times that x matches in column y (getting rid of vector y if necessary), like below..

x  A  B  C
1  2  0  1
2  1  0  0
3  0  2  0
4  1  0  2
5  0  1  0
6  2  1  2 

Any help will be appreciated, thanks

like image 937
boothtp Avatar asked Dec 10 '25 09:12

boothtp


1 Answers

You just need the table function :)

> table(X)
   y
x   A B C
  1 2 0 1
  2 1 0 0
  3 0 2 0
  4 1 0 2
  5 0 1 0
  6 2 1 2
  7 1 0 1
  8 3 1 0
like image 178
Julien Navarre Avatar answered Dec 11 '25 22:12

Julien Navarre



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!