Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Efficient Means of Identifying Number of Distinct Elements in a Row

library(dplyr)

I have the following data set

set.seed(123)
n <- 1e6
d <- data.frame(a = letters[sample(5, n, replace = TRUE)], b = letters[sample(5, n, replace = TRUE)], c = letters[sample(5, n, replace = TRUE)],  d = letters[sample(5, n, replace = TRUE)]) 

And I would like to count the number of distinct letters in each row. To do this I use

sapply(as.data.frame(t(d)), function(x) n_distinct(x))

However because this approach is implementing a loop, it is slow. Do you have an suggestions on how to speed this up?

My laptop is a piece of junk so...

system.time(sapply(as.data.frame(t(d)), function(x) n_distinct(x)))
  user  system elapsed 
185.78    0.86  208.08 
like image 597
Jacob H Avatar asked Dec 08 '25 07:12

Jacob H


2 Answers

If the different values are not so many, you can try:

d<-as.matrix(d)
uniqueValues<-unique(as.vector(d))
Reduce("+",lapply(uniqueValues,function(x) rowSums(d==x)>0))

For the example you provided, this is much faster than other solutions and yields the same result.

like image 79
nicola Avatar answered Dec 09 '25 19:12

nicola


You can try,

system.time(colSums(apply(d, 1, function(i) !duplicated(i))))
#user  system elapsed 
#6.50    0.02    6.53 
like image 25
Sotos Avatar answered Dec 09 '25 21:12

Sotos



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!