我有一个标准的'can-I-avoid-a-loop'问题,但找不到解决方案。为for循环标记连续的观察块
我回答了this question by @splaisan,但我不得不在中间部分采用一些丑陋的扭曲,用for
和多个if
测试。我希望有人能给出一个更好的答案在这里模拟一个简单的版本...
的问题
鉴于这样的数据结构:
df <- read.table(text = 'type
a
a
a
b
b
c
c
c
c
d
e', header = TRUE)
我要找出连续相同类型的块并将它们分组标记。第一个块应该标记为0,下一个为1,依此类推。无限数量的块,每块可能只有一个成员。
type label
a 0
a 0
a 0
b 1
b 1
c 2
c 2
c 2
c 2
d 3
e 4
我的解决方案
我不得不求助于for
循环要做到这一点,这里是代码:
label <- 0
df$label <- label
# LOOP through the label column and increment the label
# whenever a new type is found
for (i in 2:length(df$type)) {
if (df$type[i-1] != df$type[i]) { label <- label + 1 }
df$label[i] <- label
}
我的问题
任何人都可以做这没有循环和条件?
见'rle',最有用的r功能没有人能够找到? – joran
谢谢@joran,我可以看到如何帮助!我会探索它一段时间。我的第一个努力工作,但仍然不雅。如果我管理一个可以通过的,我会发布一个答案。 – gauden
只需将长度组件从'rle'输入到'rep'中的times参数中。 – joran