如何切割两个相同大小的矢量?

时间:2013-11-08 10:47:42

标签: r vector r-factor

所以,我有一个长度为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)

我希望在两个记录中剪切它。我尝试使用剪切,但输出是由具有相同长度的间隔定义的:(28,34.7] (34.7,41.4]

我该怎么做?

3 个答案:

答案 0 :(得分:2)

目前尚不清楚您的预期输出,但我认为您在寻找:

split(p2,cut(p2,2))

答案 1 :(得分:1)

针对您的具体案例,请尝试

> 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

或者可能是这样的?

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

答案 2 :(得分:1)

这会给你你想要的吗?

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

来自?cut2:...如果未给出cuts,则会将x剪切为分位数组(g给出)