3

我想将一个从 0-70 到 x 个类别的值向量切割,并希望每个类别的上限。到目前为止,我已经尝试过使用cut()并尝试从级别中提取限制。我有一个级别列表,我想从中提取每个级别的第二个数字。如何提取空格和 ] 之间的值(这是我感兴趣的数字)?

我有:

> levels(bins)
 [1] "(-0.07,6.94]" "(6.94,14]"    "(14,21]"      "(21,28]"      "(28,35]"     
 [6] "(35,42]"      "(42,49]"      "(49,56]"      "(56,63.1]"    "(63.1,70.1]" 

并想得到:

[1] 6.94 14 21 28 35 42 49 56 63.1 70.1

或者有没有更好的方法来计算类别的上限?

4

2 回答 2

4

这可能是一种解决方案

k <- sub("^.*\\,","", levels(bins))
as.numeric(substr(k,1,nchar(k)-1))

 [1]  6.94 14.00 21.00 28.00 35.00 42.00 49.00 56.00 63.10 70.10
于 2010-06-09T08:47:16.290 回答
1

如果您想要确切的中断值,那么您应该自己计算它们,导致cut间隔的圆形限制:

x <- seq(0,1,by=.023)
levels(cut(x, 4))
# [1] "(-0.000989,0.247]" "(0.247,0.494]"     "(0.494,0.742]"     "(0.742,0.99]"     
levels(cut(x, 4, dig.lab=10))
# [1] "(-0.000989,0.2467555]" "(0.2467555,0.4945]"    "(0.4945,0.7422445]"   
# [4] "(0.7422445,0.989989]" 

您可以查看代码以cut.default了解如何breaks计算:

if (length(breaks) == 1L) {
    if (is.na(breaks) | breaks < 2L) 
        stop("invalid number of intervals")
    nb <- as.integer(breaks + 1)
    dx <- diff(rx <- range(x, na.rm = TRUE))
    if (dx == 0) 
        dx <- abs(rx[1L])
    breaks <- seq.int(rx[1L] - dx/1000, rx[2L] + dx/1000, 
        length.out = nb)
}

如此简单的方法是获取此代码并将其放入一个函数中:

compute_breaks <- function(x, breaks) 
    if (length(breaks) == 1L) {
        if (is.na(breaks) | breaks < 2L) 
            stop("invalid number of intervals")
        nb <- as.integer(breaks + 1)
        dx <- diff(rx <- range(x, na.rm = TRUE))
        if (dx == 0) 
            dx <- abs(rx[1L])
        breaks <- seq.int(rx[1L] - dx/1000, rx[2L] + dx/1000, 
            length.out = nb)
            breaks
    }

结果是

compute_breaks(x,4)
# [1] -0.000989  0.246755  0.494500  0.742244  0.989989
于 2010-06-09T09:00:34.230 回答