Below is a sample dataset (column A and column B), and I would like to create a new flag column C to group row 3 to row 8 into a range "91345-912350" (In the real dataset, I have multiple ranges to group to). I cannot convert column A into integer, because it would cause the codes with leading 0's disappear (e.g. 0450 would become 450). Is there any way to identify a range with string data type?
Please feel free to use the following code to generate the sample dataset:
DT = data.table(
Code = c("0450", "912345", "912346","912347","912348","912349","912350","7860","X7960"),
Description = c("Desc A", "Desc B", "Desc C","Desc D","Desc E","Desc F","Desc G","Desc H","Desc I")
)
Additional Information:
(1) The codes do not need to be consecutive as the ranges are predefined. As long as a code is in between a certain range, it would go into that range group, regardless if there are any missing code(s). (e.g. If 912347 is missing , 912345, 912346, 91238, 912349, 912350 would still go to the range 912345-912350)
(2) The predefined ranges are all number ranges without letters, if the code contains letters, the Code Group column would be the same as the original Code column just like what's shown in cell C10 and cell A10.
(3) Not all codes need to be in a range, I have a list of predefined ranges I need to group the codes to. In this sample dataset, my predefined range is 912345-912350. There could be codes like 7860, 7861, 7862, but I do not need to group them into 7860-7862 as they are not in my predefined ranges. If a code does not have a range group, the Code Group would return the same value as the Code column, just like what's shown in cell C9 and cell A9.

The requirements here aren't entirely clear to me, but you can create a function to map the code to a range. E.g.
And then
or with tidyverse