【问题标题】:Extracting cumulative unique Elements from a list从列表中提取累积的唯一元素
【发布时间】:2013-09-12 06:37:21
【问题描述】:

我有一个清单:

z <- vector("list", 3)
z[[1]]=c(1,2,3,4)
z[[2]]=c(1,6,2,9)
z[[3]]=c(1,2,3,4,5)

我想创建一个列矩阵,列表中包含尽可能多的项目 (3)

A=matrix(0,3,1)

并且我希望矩阵的每一行都包含 Z 列表中以前从未见过的唯一元素的累积数量。比如,

矩阵应填充为:

     [1]
A=[1] 4
  [2] 6
  [3] 7

(4 因为每个元素都是新的,然后是 6 因为之前在 z[[1]] 中见过其他元素,然后是 7 因为 5 是唯一的新元素。)

有没有人知道这样做的好方法?我可以通过循环 3 并制作一个虚拟矩阵并使用 if 条件进行唯一和测试,以一种非常愚蠢的方式对其进行编程,但这似乎有点过分。

感谢您的宝贵时间。

【问题讨论】:

    标签: r matrix unique extract


    【解决方案1】:

    我认为您需要使用允许您进行迭代循环的东西,所以我在这里使用for 循环。我们获取所有唯一元素,对于z 中的每个元素,我们sum 中的唯一元素中的值,然后将它们删除以进行下一次迭代...

    #  Get unique elements
    elems <- unique( unlist( z ) )
    
    #  Pre allocate result vector
    tot <- numeric(length(z))
    
    for( i in 1:length(z) ){
        # How many unique elements are in this list element
        tot[i] <-  sum( z[[i]] %in% elems )
        #  Remove them from the list so they are not counted in the next iteration
        elems <- elems[ ! elems %in% z[[i]] ]       
      }
    
    #  Get the cumulative sum
    cumsum( tot )
    [1] 4 6 7
    

    【讨论】:

      【解决方案2】:

      如果性能不是真正的问题,您可以执行以下操作。如果列表/向量很长,我可以看到它很费力

      test = matrix(data = 0,ncol = 1,nrow=length(z))
      
      for (i in 1:length(z)){
        test[i,1]=length(unique(Reduce(c,z[1:i])))
      }
      
      test
           [,1]
      [1,]    4
      [2,]    6
      [3,]    7
      

      【讨论】:

        【解决方案3】:

        也许这是一种不必要的复杂处理方式,但您可以使用递归函数。

        z <- vector("list", 3)
        z[[1]]=c(1,2,3,4)
        z[[2]]=c(1,6,2,9)
        z[[3]]=c(1,2,3,4,5)
        
        f<-function(x,left=c()) {
          new<-unique(x[[1]][!(x[[1]] %in% left)])
          new.left<-c(new,left)
          if (length(x)==1) return(length(new))
          else return(c(length(new),f(x[-1],left=new.left)))
        }
        as.matrix(cumsum(f(z)),ncol=1)
        
             [,1]
        [1,]    4
        [2,]    6
        [3,]    7
        

        【讨论】:

          猜你喜欢
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 2017-06-20
          • 1970-01-01
          • 2018-01-17
          • 1970-01-01
          • 1970-01-01
          相关资源
          最近更新 更多