在R中创建序数向量

时间:2014-12-04 23:59:09

标签: r vector statistics

我有一个向量y_1,其值为0-100。我需要执行此向量序数 我需要编写代码:

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)

2 个答案:

答案 0 :(得分: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 :(得分:1)

如果您使用-InfInf,则可以定义&#34; edge&#34;案件更多&#34;包容性&#34;:

> 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 

这也清楚地表明间隔的右侧是封闭的(您的问题仅作为您的期望暗示)。