I am trying to find a way to group rows and assign an index to each group without using a loop. The difficulty is that the grouping variable num has no unique identifier; num is a vector of numbers (defined as character). I want to group all rows that match at least by any of the numbers in the vector. The vectors are of different lengths and include up to 20 numbers. Let me give an example:
I have a dataframe like this:
df <- data.frame(id = c(1:5), num = c('111;222', '333;111;444', '000;88888;1', '9999;111', '1'))
I split num by the separator ; such that every row becomes a vector:
library(dplyr)
df <- df %>%
mutate(num = str_split(num, ';'))
I want to index all rows for which at least one number in the vector matches with the same index. The result should look as follows:
id num group_index
1 c('111','222') 1
2 c('333','111','444') 1
3 c('000','88888','1') 2
4 c('9999','444') 1
5 '1' 2
The example illustrates another difficulty: Group 1 is identified by '111' as well as '444', even though row 1 is part of group 1 and does not contain '444' in num.
If num was just a string, I would do the following
df <- group_by(num) %>%
mutate(group_index = group_indices(.,num))
Now, I thought I should perhaps start by identifying groups. A first approach, which does not work is:
df <- df %>%
group_by_if(num, any(num, str_c(num, collapse = '|')) == T)
I know that I could start by writing a loop. However, R is not very efficient with loops, so I would prefer a solution without a loop – if there is any? Any hints would help!
