JMarcelino
JMarcelino

Reputation: 984

How to cut a vector in two of the same size?

So , I have a vector with length of 114:

p2<-c(28.00, 28.00, 28.00, 28.00, 28.00, 28.00, 28.37, 28.37, 28.37, 28.37, 28.37,
     28.37, 28.37, 28.37, 28.37, 28.37, 28.37, 28.37, 28.37,28.37, 28.37, 28.45,
     28.45, 28.45 ,28.45, 31.37, 31.37 ,31.37, 31.37, 31.37, 31.37, 31.37, 31.37,
     31.37, 31.37, 31.37, 31.37 ,31.37, 36.37, 36.37, 36.37 ,36.37, 38.00, 38.00,
     38.00, 38.00, 38.00, 38.00, 38.00, 38.00, 38.00, 38.00, 38.00, 38.00, 38.00,
     38.00 ,38.00, 38.00, 38.00 ,38.00, 38.00, 38.00, 38.00,38.00, 38.00, 38.00,
     38.00, 38.00, 38.00, 38.00, 38.37, 38.37, 38.37, 38.37, 38.37, 38.37, 38.37,
     38.37, 38.37, 38.37, 38.37, 38.37, 41.37, 41.37, 41.37, 41.37, 41.37, 41.37,
     41.37, 41.37, 41.37, 41.37, 41.37, 41.37, 41.37, 41.37, 41.37, 41.37, 41.37,
     41.37, 41.37, 41.37, 41.37, 41.37, 41.37, 41.3,7, 41.37, 41.37, 41.37, 41.37,
     41.37, 41.37, 41.37, 41.3)

and I want to cut it in two of the number of records. I've tried to use cut, but the output is defined by intervals with the same length: (28,34.7] (34.7,41.4]

How do I do that?

Upvotes: 0

Views: 396

Answers (3)

Jilber Urbina
Jilber Urbina

Reputation: 61204

For your particular case try

> set.seed(1)
> p2 <- runif(114, 28, 42)  # random data
> 
> ind <- 1:(length(p2)/2) # index for cutting the vector
> p2.1 <- p2[ind]         # first subvector
> p2.2 <- p2[-ind]        # second subvector
> 
> length(p2.1)            # length of first subvector
[1] 57
> length(p2.2)            # length of second subvector
[1] 57

Or maybe something like this?

> vec <- setNames(p2, cut(p2,2, labels=c("V1", "V2")))
> is.vector(vec)  # one vector 
[1] TRUE

Upvotes: 1

Henrik
Henrik

Reputation: 67778

Does this give you what you want?

library(Hmisc)
cut2(p2, g = 2)

From ?cut2: ...if cuts are not given, will cut x into quantile groups (g given)

Upvotes: 1

agstudy
agstudy

Reputation: 121588

It is not clear your expected output , but I think you look for:

split(p2,cut(p2,2))

Upvotes: 2

Related Questions