In R, apply a cut (segmentation) of one vector to another
Here is an example of the problem I am having:
I have a vector v:
v <- 1:10
I can use Hmisc::cut2
to split it evenly into 5 groups for which I first need:
library(Hmisc) cut2(v, g=5)
To check:
table(cut2(v, g=5))
[1, 3) [3, 5) [5, 7) [7, 9) [9,10]
2 2 2 2 2
Now I have another vector:
v2 <- 1:8
I want to apply the same segment v to v2 that there are also 5 groups for v2, whereas the last group [9, 10] has 0 element. Is there an easy way to do this? Thank!
+3
xiaoxiao87
source
to share
2 answers
Another way is to use v2
for indexing fromcut2(v, g = 5)
table(cut2(v, g = 5)[v2])
# [1, 3) [3, 5) [5, 7) [7, 9) [9,10]
# 2 2 2 2 0
+2
David Arenburg
source
to share
Does this work for you?
table(cut2(v2,cuts=c(1,3,5,7,9,10)))
[ 1, 3) [ 3, 5) [ 5, 7) [ 7, 9) [ 9,10]
2 2 2 2 0
+2
Justin klevs
source
to share