Ronak Kumar
Ronak Kumar

Reputation: 69

Create new column based on some condition in R

Can you someone please help me to write R code for below question?

Using below data, I would like to add a third column 'x' which starts from 1 in the first row and remains 1 till my year hits 1 at which point it the column x becomes '2' (row 12) and again becomes 3 in row (23) and so on..

data <- structure(list(year = c(1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 1, 
2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 1, 2), pattern_values = c("41", 
"59", "69", "75", "85", 
"43", "45", "48", "52", 
"56", "0", "748", "728", 
"701", "670", "645", "53", 
"55", "59", "63", "69", 
"0", "918", "717")), row.names = c(NA, 
-24L), class = c("tbl_df", "tbl", "data.frame"))

Upvotes: 1

Views: 54

Answers (2)

akrun
akrun

Reputation: 887731

We could do this in a more general way i.e. assuming that 1 is missing in any of the cases, then also this would work

with(data, cumsum(c(TRUE, diff(year) < 0)))
#[1] 1 1 1 1 1 1 1 1 1 1 1 2 2 2 2 2 2 2 2 2 2 2 3 3

Upvotes: 1

Ronak Shah
Ronak Shah

Reputation: 389225

We can use cumsum :

data$x <- cumsum(data$year == 1)
data$x
#[1] 1 1 1 1 1 1 1 1 1 1 1 2 2 2 2 2 2 2 2 2 2 2 3 3

Upvotes: 2

Related Questions