

Increase by 1 for each column change in R
source link: https://www.codesd.com/item/increase-by-1-for-each-column-change-in-r.html
Go to the source link to view the article. You can view the picture content, updated content and better typesetting reading experience. If the link is broken, please click the button below to view the snapshot at that time.

Increase by 1 for each column change in 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
Building on Mr Flick answer:
df$var2 <- cumsum(c(0,as.numeric(diff(df$var1))!=0))
But if you don't want to use diff
you can still use:
df$var2 <- c(0,cumsum(as.numeric(with(df,var1[1:(length(var1)-1)] != var1[2:length(var1)]))))
It starts at 0, not at 1 but I'm sure you see how to change it if you want to.
Recommend
-
15
Weeknotes 14: capitalism has largely been a way of not needing each other 21 June 2019 Via Richard D. Barlett, I listened to
-
9
Responses (43)
-
4
Change the equation of the column in SQL advertisements I am using MS SQL Server and I have a multiple columns and databases already made. 3 o...
-
6
3 Simple Things You Can Do Each Day to Increase Fat LossIt’s not about calories in vs. calories out.Photo by Anastase Maragos on
-
19
VBA / Access - Creating a new table for each change in a field advertisements I am trying to write in VBA for Access. I have a table with seve...
-
7
How To Change Column Order Using Pandas Filed Under: PandasIn this article, we’ll learn how to change...
-
10
SQL: Select the sum of each individual value of a column advertisements There is a column that can have several...
-
4
How to Change Column Name and Type in Laravel Migration 2657 views 6 months ago Laravel In the working with MySQL d...
-
12
Apple may change its iPhone business strategy to increase profit...
-
15
Nintendo confirms that Switch prices will not change in response to PS5 increases...
About Joyk
Aggregate valuable and interesting links.
Joyk means Joy of geeK