代码之家  ›  专栏  ›  技术社区  ›  Stedy

基于范围在r中创建分类变量

  •  9
  • Stedy  · 技术社区  · 14 年前

    我有一个带有一列整数的数据框,我想用它作为一个引用来创建一个新的分类变量。我想把变量分成三组,并自己设置范围(即0-5、6-10等)。我试过 cut 但这会根据正态分布将变量分组,我的数据是右偏的。我也尝试过使用if/then语句,但这会输出一个true/false值,我希望保留我的原始变量。我确信有一个简单的方法可以做到这一点,但我似乎想不出来。有什么简单的快速方法的建议吗?

    我有这样的想法:

    x   x.range
    3   0-5
    4   0-5
    6   6-10
    12  11-15
    
    3 回复  |  直到 6 年前
        1
  •  12
  •   doug    10 年前

    伊恩的回答( )据我所知,这是最常见的方法。

    我更喜欢用 木瓦 ,从 点阵 包裹

    在我看来,指定装箱间隔的参数更直观一些。

    你用 木瓦 像这样:

    # mock some data
    data = sample(0:40, 200, replace=T)
    
    a = c(0, 5);b = c(5,9);c = c(9, 19);d = c(19, 33);e = c(33, 41)
    
    my_bins = matrix(rbind(a, b, c, d, e), ncol=2)
    
    # returns: (the binning intervals i've set)
            [,1] [,2]
     [1,]    0    5
     [2,]    5    9
     [3,]    9   19
     [4,]   19   33
     [5,]   33   41
    
    shx = shingle(data, intervals=my_bins)
    
    #'shx' at the interactive prompt will give you a nice frequency table:
    # Intervals:
       min max count
    1   0   5    23
    2   5   9    17
    3   9  19    56
    4  19  33    76
    5  33  41    46
    
        2
  •  17
  •   Ian Fellows    14 年前
    x <- rnorm(100,10,10)
    cut(x,c(-Inf,0,5,6,10,Inf))
    
        3
  •  1
  •   moodymudskipper    6 年前

    我们可以使用 smart_cut 从包装 cutr :

    devtools::install_github("moodymudskipper/cutr")
    library(cutr)
    
    x <- c(3,4,6,12)
    

    从1开始以5长度间隔切割:

    smart_cut(x,list(5,1),"width" , simplify=FALSE)
    # [1] [1,6)   [1,6)   [6,11)  [11,16]
    # Levels: [1,6) < [6,11) < [11,16]
    

    要准确获取请求的输出:

    smart_cut(x,c(0,6,11,16), labels = ~paste0(.y[1],'-',.y[2]-1), simplify=FALSE, open_end = TRUE)
    # [1]   0-5   0-5  6-10 11-15
    # Levels:   0-5 <  6-10 < 11-15
    

    more on cutr and smart_cut

    推荐文章