r - 在没有 for 循环的情况下标记连续的观察 block

标签 r

我有一个标准的“我可以避免循环”问题,但找不到解决方案。

我回答了 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 <- rle(as.numeric(df$type))
df$label <- rep(seq(from=0, length=length(r$lengths)), times=r$lengths)

不使用 rle , 但是 cumsum在被强制为数字的逻辑上。
df$label <- c(0,cumsum(df$type[-1] != df$type[-length(df$type)]))

两者都给出:
> df
   type label
1     a     0
2     a     0
3     a     0
4     b     1
5     b     1
6     c     2
7     c     2
8     c     2
9     c     2
10    d     3
11    e     4

关于r - 在没有 for 循环的情况下标记连续的观察 block ,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10609772/

相关文章:

r - 带for循环的数据汇总

r - 在 R 中导入数百万个文件的最快方法?

r - 数据框的列名称中的单词之间的空格会导致 Shiny 的应用程序出现问题

regex - R:如何将字符串的一部分转换为变量名并在同一字符串中返回其值?

r - 为每个观察添加频率列

r - ggplot : overlay two plots

R - 根据先前迭代的结果应用或 for 循环

r - 如何计算文档中单词与特定术语的接近度

r - 两个字符串相减

python - 等效于 Python/pandas 中 R/ddply 中的转换?