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)])
我想计算每一行中不同字母的数量。为此,我使用
sapply(as.data.frame(t(d)), function(x) n_distinct(x))
然而,因为这种方法正在实现循环,所以它很慢。你对如何提高速度有什么建议吗?
我的笔记本电脑是一块垃圾......
system.time(sapply(as.data.frame(t(d)), function(x) n_distinct(x)))
user system elapsed
185.78 0.86 208.08
答案 0 :(得分:5)
如果不同的值不是很多,您可以尝试:
d<-as.matrix(d)
uniqueValues<-unique(as.vector(d))
Reduce("+",lapply(uniqueValues,function(x) rowSums(d==x)>0))
对于您提供的示例,这比其他解决方案快得多,并产生相同的结果。
答案 1 :(得分:4)
你可以尝试,
system.time(colSums(apply(d, 1, function(i) !duplicated(i))))
#user system elapsed
#6.50 0.02 6.53
答案 2 :(得分:3)
以下是一些比OP方法更快(在我的机器上)的选项(其他帖子中包含的方法)
system.time({ #@nicola's function
d<-as.matrix(d)
uniqueValues<-unique(as.vector(d))
Reduce("+",lapply(uniqueValues,function(x) rowSums(d==x)>0))
})
# user system elapsed
# 0.61 0.00 0.61
system.time(colSums(apply(d, 1, function(i) !duplicated(i)))) #@Sotos function
# user system elapsed
# 8.16 0.00 8.18
system.time(apply(d, 1, function(x) sum(!duplicated(x))))
# user system elapsed
# 8.19 0.01 8.25
system.time(apply(d, 1, uniqueN)) #uniqueN from `data.table`
# user system elapsed
# 15.59 0.03 15.74
system.time(apply(d, 1, n_distinct)) #n_distinct from `dplyr`
# user system elapsed
# 31.50 0.04 53.82
system.time(sapply(as.data.frame(t(d)), function(x) n_distinct(x)))
# user system elapsed
# 70.12 0.36 72.03