2014-12-04 82 views
0

我从0-100.I矢量Y_1机智值需要这样做向量顺序 我需要编写此:创建R中的序矢量

Y=1 if y_1 <=20 

    Y=2 if y_1 between 20 and 40 
    Y=3 if y_1 between 40 and 60 
    Y=4 if y_1 between 60 and 80 
    Y=5 if y_1 > 80 

我试过,但我不能名称序号:

findInterval(y_1, c(0,20,40,60,80)) 
cut(y_1, breaks=c(0,20, 40, 60, 80, 100),ordered_result=TRUE) 

回答

1

这是你的载体。

y_1 <- 0:100 

首先,我们来定义分割的阈值。

vectorThresholds <- c(20, 40, 60, 80, Inf) 

然后,我们可以定义一个新的向量,它包含一个对应于间隔的数字。

y_2 <- sapply(y_1, function(el){ 
    min(which(el < vectorThresholds)) 
}) 

为了命名关卡,您可以使用因子。

y_3 <- factor(y_2, labels = c("1st", "2nd", "3rd", "4th", "5th")) 
1

如果使用-InfInf可以定义“边缘”的情况下更多的“inclusifvely”:

> table(cut(y_1, c(-Inf,20,40,60,80, Inf), rightmost.closed=TRUE)) 

(-Inf,20] (20,40] (40,60] (60,80] (80, Inf] 
     21  20  20  20  20 

这也留下明显,间隔的右侧被关闭(这你的问题只是暗示在你的期望)。