【发布时间】: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 <- grep("[[:upper:]]", d$v1) ; aggregate(idx ~ cumsum(c(FALSE, diff(idx) != 1)), FUN=range)