user2071938
user2071938

Reputation: 2265

Split vector in groups

How can I split a vector into groups in R?

I have a numerical vector

 [1] 3.5 3.0 3.2 3.1 3.6 3.9 3.4 3.4 2.9 3.1 3.7 3.4 3.0 3.0 4.0 4.4 3.9 3.5 3.8 3.8 3.4     3.7 3.6
[24] 3.3 3.4 3.0 3.4 3.5 3.4 3.2 3.1 3.4 4.1 4.2 3.1 3.2 3.5 3.6 3.0 3.4 3.5 2.3 3.2 3.5 3.8 3.0
[47] 3.8 3.2 3.7 3.3

and want to group them by there value,

minValue = 2.0 
maxValue = 4.5 //rounded to next 0.5

so I want (4.5-2.0)/0.5 = 5 groups

1 group >=2.0 x < 2.5
2 group >=2.5 x < 3.0
3 group >=3.0 x < 3.5
4 group >=3.5 x < 4.0
5 group >=4.0 x < 4.5

any ideas how I can do that without loops?

Upvotes: 0

Views: 376

Answers (1)

gagolews
gagolews

Reputation: 13076

Use the split and cut functions:

(x <- round(runif(50, 2, 4.5), 1)) # exemplary data
## [1] 3.9 3.1 2.8 3.7 4.2 4.4 2.0 3.3 3.5 2.2 3.3 4.2 2.6 3.6 3.6 3.2 3.4 2.9 3.5 2.1 2.9 3.6 3.9 2.4 3.9 3.1
## [27] 4.2 2.8 2.7 2.1 2.1 3.0 2.2 2.5 4.3 2.8 2.0 2.2 2.3 2.2 3.8 2.2 2.1 4.1 3.9 2.1 2.1 2.3 2.2 3.1

split(x, cut(x, seq(2,4.5,by=0.5), right=FALSE))
## $`[2,2.5)`
##  [1] 2.0 2.2 2.1 2.4 2.1 2.1 2.2 2.0 2.2 2.3 2.2 2.2 2.1 2.1 2.1 2.3 2.2
## 
## $`[2.5,3)`
## [1] 2.8 2.6 2.9 2.9 2.8 2.7 2.5 2.8
## 
## $`[3,3.5)`
## [1] 3.1 3.3 3.3 3.2 3.4 3.1 3.0 3.1
## 
## $`[3.5,4)`
## [1] 3.9 3.7 3.5 3.6 3.6 3.5 3.6 3.9 3.9 3.8 3.9
##
## $`[4,4.5)`
## [1] 4.2 4.4 4.2 4.2 4.3 4.1

The above call returns a list of numeric vectors.

Upvotes: 3

Related Questions