首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >应用程序的优化

应用程序的优化
EN

Stack Overflow用户
提问于 2019-08-02 03:01:15
回答 1查看 77关注 0票数 0

我有计算数据帧/矩阵的一致性值的现有代码。它基本上是所有值在总行数上都相同的行数。

代码语言:javascript
复制
...
concordance<-new[complete.cases(new),] #removes rows with NAs
TF<-apply(concordance, 1, function(x) if(length(unique(x))>1) F else T)
#outputs vector of T/F if it is concordant
numF<-table(TF)["TRUE"]#gets number of trues
concValue<-numF/NROW(TF) #true/total
...

以上就是我现在所拥有的。它运行得很好,但我想知道是否有任何方法可以让它更快。

编辑:对象的维度是可变的,但是cols的数量通常是2-6,并且通常有1,000,000+行。这是我正在开发的包的一部分,因此输入数据是可变的。

EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2019-08-02 04:37:54

因为行数比列数多得多,所以有必要在列上循环,删除行,其中进程中有多个不同的值:

代码语言:javascript
复制
propIdentical <- function(Mat){
    nrowInit <- nrow(Mat)  

    for(i in 1:(ncol(Mat) - 1)){
       if(!nrow(Mat)) break #stop if the matrix has no rows
       else{
            #check which elements of column i and column i+1 are equal:
            equals <- Mat[,i] == Mat[, i+1] 

            # remove all other rows from the matrix
            Mat <- Mat[equals,,drop = F]
       }
    }

    return(nrow(Mat)/nrowInit)
}

一些测试:

代码语言:javascript
复制
set.seed(1)

# normal case
dat <- matrix(sample(1:10, rep = T, size = 3*10^6), nrow = 10^6)
system.time(prI <- propIdentical(dat)) ; prI

 user  system elapsed 
 0.053   0.017   0.070 
[1] 0.009898

# normal case on my pc for comparison:
system.time(app <- mean(apply(dat, 1, function(x) length(unique(x))) == 1L)); app
   user  system elapsed 
 12.176   0.036  12.231 
[1] 0.009898

# worst case
dat <- matrix(1L, nrow = 10^6, ncol = 6)
> system.time(prI <- propIdentical(dat)) ; prI
   user  system elapsed 
  0.302   0.044   0.348 
[1] 1
# worst case on my pc for comparison
system.time(mean(apply(dat, 1, function(x) length(unique(x))) == 1L))
   user  system elapsed 
 12.562   0.001  12.578

# testing drop = F and if(!nrow(Mat)) break
dat <- matrix(1:2, ncol = 2)
> system.time(prI <- propIdentical(dat)) ; prI
   user  system elapsed 
      0       0       0 
[1] 0

注意:如果在data.frame上运行,请确保首先将其转换为矩阵。

票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/57315488

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档