Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

assign value from one vector to a group based on another vector in R

I have 2 vectors:

v1 = c(4, 8, 13)
v2 = 1:20

I want to classify each element in v2 to a specific group depending on the element comparison. In this example, values 1:4 from v2 will be classed to group1, values 5:8 to group2, values 9:13 to group3, and values 14:20 to group4.

I would like to have a final df like

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

enter image description here

Any suggestions

>Solution :

We may use %in% with cumsum to create the index and paste ‘group’

data.frame(ls2 = v2, group = paste0("group", cumsum(v2 %in% (v1 + 1)) + 1))

-output

 ls2  group
1    1 group1
2    2 group1
3    3 group1
4    4 group1
5    5 group2
6    6 group2
7    7 group2
8    8 group2
9    9 group3
10  10 group3
11  11 group3
12  12 group3
13  13 group3
14  14 group4
15  15 group4
16  16 group4
17  17 group4
18  18 group4
19  19 group4
20  20 group4
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading