识别连续不同元素数量的有效方法 [英] Efficient Means of Identifying Number of Distinct Elements in a Row

查看:52
本文介绍了识别连续不同元素数量的有效方法的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

library(dplyr)

我有以下数据集

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 

推荐答案

如果不同的值不是很多,可以尝试:

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.

这篇关于识别连续不同元素数量的有效方法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆