Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Increment by 1 for every change in column

Tags:

r

Lets say I have the following data frame

set.seed(123)
df <- data.frame(var1=(runif(10)>0.5)*1)

var1 could have any type / number of levels not specifically 0 and 1s

I would like to create a var2 which increments by 1 every time var1 changes without using a for loop

Expected result in this case is:

data.frame(var1=(runif(10)>0.5)*1, var2=c(1, 2, 3, 4, 4, 5, 6, 6, 6, 7))

var1 var2
   0    1
   1    2
   0    3
   1    4
   1    4
   0    5
   1    6
   1    6
   1    6
   0    7

Another option for the data frame could be:

df <- data.frame(var1=c("a", "a", "1", "0", "b", "b", "b", "c", "1", "1"))

in this case the result should be:

var1 var2
   a    1
   a    1
   1    2
   0    3
   b    4
   b    4
   b    4
   c    5
   1    6
   1    6
like image 612
dimitris_ps Avatar asked Apr 15 '15 21:04

dimitris_ps


People also ask

How do you add +1 in Excel?

How do I add the number "1" in front of all numbers in a column in Excel? I have a column of phone numbers that need the "1" added to them. Create a custom number format: Type 1-(000) 000–0000 in the “Type:” box.


1 Answers

How about using diff() and cumsum(). For example

df$var2 <- cumsum(c(1,diff(df$var1)!=0))
like image 90
MrFlick Avatar answered Sep 21 '22 19:09

MrFlick