【发布时间】:2012-05-23 11:57:25
【问题描述】:
我有一个标准的“can-I-avoid-a-loop”问题,但找不到解决方案。
我回答了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,我知道这会有什么帮助!我会探索一段时间。我的第一次努力正在奏效,但仍然不够优雅。如果我管理一个可以接受的答案,我会发布一个答案。
-
只需将
rle中的长度分量输入到rep中的时间参数中。
标签: r