Constantin
Constantin

Reputation: 154

Assign a unique ID while a condition is FALSE in r

I need to assign unique IDs, however, there is not identifying variables other than when size decreases. I have created a vector of TRUE/FALSE statements and I want to assign an ID to each row while the statement is FALSE. Every time a TRUE statement is then passed, I want to assign a new ID to the rows and this ID to continue while the statement is FALSE.

A sample of my dataset:

     Size    index
1    8.70    FALSE
2    9.40    FALSE
3   10.00    FALSE
4   10.50    FALSE
5   11.00    FALSE
6    1.60    TRUE
7    2.20    FALSE
8    2.60    FALSE
9    3.30    FALSE
10   3.70    FALSE
11   1.10    TRUE
12   2.40    FALSE
13   2.80    FALSE
14   3.40    FALSE
15   4.90    FALSE
16   6.20    FALSE
17   1.90    TRUE
18   2.20    FALSE
19   3.30    FALSE
20   4.80    FALSE

I have tried using the following code

x$index[1] <- FALSE
RandomID <- sample(100:999, size = 1000, replace = TRUE)
for(i in 1:len){
  int <- sample(RandomID,1,replace = FALSE)
  if(x$index[i] == FALSE) {
    print(int)
  }else{break}
}

Upvotes: 0

Views: 246

Answers (1)

Ian Campbell
Ian Campbell

Reputation: 24838

You can use cumsum from base R:

x$id <- cumsum(x$index) + 1 
x
#   Size index id
#1   8.7 FALSE  1
#2   9.4 FALSE  1
#3  10.0 FALSE  1
#4  10.5 FALSE  1
#5  11.0 FALSE  1
#6   1.6  TRUE  2
#7   2.2 FALSE  2
#8   2.6 FALSE  2
#9   3.3 FALSE  2
#10  3.7 FALSE  2
#11  1.1  TRUE  3
#12  2.4 FALSE  3

Data

x <- structure(list(Size = c(8.7, 9.4, 10, 10.5, 11, 1.6, 2.2, 2.6, 
3.3, 3.7, 1.1, 2.4, 2.8, 3.4, 4.9, 6.2, 1.9, 2.2, 3.3, 4.8), 
    index = c(FALSE, FALSE, FALSE, FALSE, FALSE, TRUE, FALSE, 
    FALSE, FALSE, FALSE, TRUE, FALSE, FALSE, FALSE, FALSE, FALSE, 
    TRUE, FALSE, FALSE, FALSE), id = c(1, 1, 1, 1, 1, 2, 2, 2, 
    2, 2, 3, 3, 3, 3, 3, 3, 4, 4, 4, 4)), row.names = c("1", 
"2", "3", "4", "5", "6", "7", "8", "9", "10", "11", "12", "13", 
"14", "15", "16", "17", "18", "19", "20"), class = "data.frame")

Upvotes: 2

Related Questions