pogibas
pogibas

Reputation: 28329

Cut vector into groups

a <- -30:30
cutSize <- 10
b <- a %/% cutSize
table(b)
# Output
-3 -2 -1  0  1  2  3 
10 10 10 10 10 10  1 

Wanted output

-3 -2 -1  0  1  2  3 
10 10 10  1 10 10  10

I need to divide vector into groups (by cutSize). Always used %/%, but apparently it "shifts" my groups. I want to group:

Upvotes: 1

Views: 103

Answers (1)

David Arenburg
David Arenburg

Reputation: 92282

Here's a bit awkword solution

table(ceiling((a / cutSize) * sign(a)) * sign(a))
# -3 -2 -1  0  1  2  3 
# 10 10 10  1 10 10 10 

Or similarly

table(ceiling(abs(a / cutSize)) * sign(a))
# -3 -2 -1  0  1  2  3 
# 10 10 10  1 10 10 10 

Upvotes: 4

Related Questions