Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

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

enter image description here

Any suggestions

like image 304
frank Avatar asked Nov 29 '25 12:11

frank


1 Answers

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
like image 126
akrun Avatar answered Dec 01 '25 02:12

akrun



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!