gpt4 book ai didi

r - 查找数据为大写的范围的开始和结束

转载 作者:行者123 更新时间:2023-12-04 12:12:06 24 4
gpt4 key购买 nike

我有一个 data.frame ystr:

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

我想在 CAPS 中找到每组字母的开始和结束,所以我的输出是:
    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但我无法弄清楚它在这种情况下如何适用。

最佳答案

您可以通过计算二进制指示符的运行长度编码 ( 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

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

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

关于r - 查找数据为大写的范围的开始和结束,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34388469/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com