我有一个标准的“我可以避免循环”问题,但找不到解决方案。
我回答了这个问题由@splaisan提出 https://stackoverflow.com/questions/10532192/add-segments-to-scatter-plot/10559398#10559398但我不得不在中间部分诉诸一些丑陋的扭曲,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
}
我的问题
任何人都可以在没有循环和条件的情况下做到这一点吗?
Using rle
r <- rle(as.numeric(df$type))
df$label <- rep(seq(from=0, length=length(r$lengths)), times=r$lengths)
不使用rle
, but 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
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)