【问题标题】:Count how many times an element is repeated or not repeated in a sequence (R)计算一个元素在序列中重复或不重复的次数 (R)
【发布时间】:2016-07-06 14:28:25
【问题描述】:

我有一系列事件,编码为 A、B 和 C。对于每个元素,我需要计算该元素之前重复了多少次,但如果不重复,则计数器应每行减一.在第一次遇到每个项目时,它的计数器为零。例如:

x<-c('A','A','A','B','C','C','A','B','A','C')
y<-c(0,1,2,0,0,1,-2,-4,-4,-3)
cbind(x,y)

      x   y   
 [1,] "A" "0" 
 [2,] "A" "1" 
 [3,] "A" "2" 
 [4,] "B" "0" 
 [5,] "C" "0" 
 [6,] "C" "1" 
 [7,] "A" "-2"
 [8,] "B" "-4"
 [9,] "A" "-4"
[10,] "C" "-3"

我需要从 x 生成列 y。我知道我可以使用rle 作为运行长度,但我不知道如何从上次遇到特定事件后获得时间来减少计数器。

【问题讨论】:

  • 抱歉,小错误,第 7 行的值应该是 -2。在第 7 行事件 == 'A' 上,'A' 计数器的先前值为 2(第 3 行),因此第 4 行计数器 = 1,第 5 行计数器 = 0,第 6 行计数器 = -1,第 3 行7 计数器 =-2。 B 也是如此 - B 的最后一个计数器值为 0,并且自上一个 B 以来有 4 行。如果当前事件与前一行相同,则计数器加一,如果不是,则减一,并且每种事件类型都有单独的计数器。
  • 还修复了第 9 行的 A 值,那里也有错误。当我计算事物时会发生这种情况。

标签: r sequence


【解决方案1】:

我认为这是一种解决问题的R 方式。我们可以用同样的方法计算x中所有不同元素的索引,将其偏移其初始位置,然后将它们组合在一起。

分别计算 x 中每个唯一元素的索引:

library(data.table)
sepIndex <- lapply(unique(x), function(i) { 
    s = cumsum(ifelse(duplicated(rleid(x == i)) & x == i, 1, -1)) + min(which(x == i)); 
    # use `rleid` with `duplicated` to find out the duplicated elements in each block.
    # and assign `1` to each duplicated element and `-1` otherwise and use cumsum for cumulative index
    # offset the index by the initial position of the element `min(which(x == i))`
    replace(s, x != i, NA) 
})

这为我们提供了每个唯一元素的索引列表:

sepIndex
# [[1]]
#  [1]  0  1  2 NA NA NA -2 NA -4 NA

# [[2]]
#  [1] NA NA NA  0 NA NA NA -4 NA NA

# [[3]]
#  [1] NA NA NA NA  0  1 NA NA NA -3

使用Reduce 函数将列表合二为一,应该可以满足您的需求:

Reduce(function(x, y) ifelse(is.na(x), y, x), sepIndex)
#  [1]  0  1  2  0  0  1 -2 -4 -4 -3

【讨论】:

    【解决方案2】:

    还有另一种使用base R的方法

    positions <- sapply(unique(x),function(t) which(x %in% t))
    values <- sapply(sapply(positions,diff),function(s) c(0,cumsum(ifelse(s>1,-s,s))))
    df <- data.frame(positions=unlist(positions),values=unlist(values))
    df[with(df,order(positions)),2]
    

    【讨论】:

      猜你喜欢
      • 2016-04-21
      • 2012-06-11
      • 2023-03-11
      • 2020-06-27
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2017-05-10
      • 1970-01-01
      相关资源
      最近更新 更多