I am working with data structured somewhat like the following:
testdat <- data.frame(MyDat = c("a","a","b","b","b","a","a","a","a","b"))
I would like to create a counter variable MyCount
that iterates along MyDat
, breaking and adding 1 to the count whenever there is a shift in the factor level of 'MyDat. Ideally, the result would look something like this:
MyCount | MyDat |
---|---|
1 | a |
1 | a |
2 | b |
2 | b |
2 | b |
3 | a |
3 | a |
3 | a |
3 | a |
4 | b |
I am struggling with trying to figure out how to set this loop up for checking whether one row value is equivalent to the previous row and if not then breaking and adding one to the counter. It also appears I need to start iterating only on the second row onward. Something like:
testdat <- data.frame(MyDat = c("a","a","b","b","b","a","a","a","a","b"))
v <- vector(mode = "integer", length = length(testdat))
counter <- 1
for(i in v) {
if(testdat[, MyDat] == testdat[i-1, MyDat]) {
counter
} else {
counter = counter + 1
}
both <- cbind(v, testdat)