【问题标题】:Find start and end of ranges where data is upper case查找数据为大写的范围的开始和结束
【发布时间】:2015-12-21 03:17:24
【问题描述】:

我有一个 data.frame ystr:

    v1
1    a
2    B
3    B
4    C
5    d
6    a
7    B
8    D

我想在大写字母中找到每组字母的开头和结尾,所以我的输出是:

    groupId startPos    endPos
1   1       2           4
2   2       7           8

我可以通过按顺序查看每个元素并将其与之前的元素进行比较来使用 for 循环,如下所示:

currentGroupId <-0

for (i in 1:length(ystr[,1])){ 
  if (grepl("[[:upper:]]", ystr[i,])) 
  { 
    if (startCounter == 0) 
    {
       currentGroupId <- currentGroupId +1
       startCounter <-1 
       mygroups[currentGroupId,] <- c(currentGroupId, i, 0)
    }
  }else if (startCounter == 1){
    startCounter <-0
    mygroups[currentGroupId,3]<- i-1
  }
}

在 R 中有一种简单的方法吗?

这可能类似于Mark start and end of groups,但我不知道它在这种情况下如何应用。

【问题讨论】:

  • idx &lt;- grep("[[:upper:]]", d$v1) ; aggregate(idx ~ cumsum(c(FALSE, diff(idx) != 1)), FUN=range)

标签: r aggregate


【解决方案1】:

您可以通过计算您的数据是否为大写的二进制指示符的游程编码 (rle) 来做到这一点,这取决于数据在转换为大写时是否等于自身。

with(rle(d[,1] == toupper(d[,1])),
     data.frame(start=cumsum(lengths)[values]-lengths[values]+1,
                end=cumsum(lengths)[values]))
#   start end
# 1     2   4
# 2     7   8

您可以通过查看Stack Overflow answers using this command 来查看使用rle 的其他示例。

数据:

d <- data.frame(v1=c("a", "B", "B", "C", "d", "a", "B", "D"))

【讨论】:

    【解决方案2】:

    您可以使用IRanges 包。基本上是找到连续的范围。

    d <- data.frame(v1=c("a", "B", "B", "C", "d", "a", "B", "D"))
    d.idx <- which(d$v1 %in% LETTERS)
    d.idx
    # [1] 2 3 4 7 8
    
    library(IRanges)
    d.idx.ir <- IRanges(d.idx, d.idx)
    reduce(d.idx.ir)
    # IRanges of length 2
    #     start end width
    # [1]     2   4     3
    # [2]     7   8     2
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2012-10-18
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多