I have a standard "can-I-avoid-a-loop" problem, but cannot find a solution.
I answered this question @splaisan , but I had to resort to some ugly distortions in the middle part with tests forand multiple if. I am imitating a simpler version here, hoping that someone can give a better answer ...
PROBLEM
For a data structure like this:
df <- read.table(text = 'type
a
a
a
b
b
c
c
c
c
d
e', header = TRUE)
I want to identify adjacent pieces of the same type and mark them in groups. The first fragment should be marked as 0, the next 1 and so on. There is an indefinite number of fragments, and each fragment can be short as soon as one member.
type label
a 0
a 0
a 0
b 1
b 1
c 2
c 2
c 2
c 2
d 3
e 4
MY DECISION
I had to resort to a loop forto do this, here is the code:
label <- 0
df$label <- label
for (i in 2:length(df$type)) {
if (df$type[i-1] != df$type[i]) { label <- label + 1 }
df$label[i] <- label
}
MY QUESTION
- ?