【问题标题】:Assign data to levels produced by cut (R)将数据分配给 cut (R) 生成的级别
【发布时间】:2016-02-20 20:52:51
【问题描述】:

我有一个使用cut 创建的因子变量:

mycuts=cut(c(1,2,3,4,5,6,7,8),breaks = 3)
mycuts
[1] (0.993,3.33] (0.993,3.33] (0.993,3.33] (3.33,5.67]  (3.33,5.67] 
[6] (5.67,8.01]  (5.67,8.01]  (5.67,8.01] 
Levels: (0.993,3.33] (3.33,5.67] (5.67,8.01]

现在我想将向量 otherdata 分配到与 cut 相同的间隔。

otherdata=c(4,8)

一个新的cut 总是为otherdata 具有与data 不同的级别,我只能设置标签。

所以,我试过了

factor(otherdata,levels=levels(mycuts))

[1] <NA> <NA>
Levels: (0.993,3.33] (3.33,5.67] (5.67,8.01]

但它不起作用。

期望的行为(评论更新):

[1] (3.33,5.67] (5.67,8.01] 等级:(0.993,3.33] (3.33,5.67] (5.67,8.01]

【问题讨论】:

    标签: r r-factor


    【解决方案1】:
    # breaks vector obtained in a way suggested in ?cut
    breaks <- unique(as.numeric(c(sub("\\((.+),.*", "\\1", mycuts), 
                                  sub("[^,]*,([^]]*)\\]", "\\1", mycuts))))
    cut(c(4, 8), breaks = breaks)
    # [1] (3.33,5.67] (5.67,8.01]
    # Levels: (0.993,3.33] (3.33,5.67] (5.67,8.01]
    

    【讨论】:

    • 未定义 labs 对象。
    • 我接受您的回答,因为它确实符合您的要求! cut 默认间隔与最小/最大值不一致,所以我更喜欢 include.lowest=TRUE 也包括在内。
    【解决方案2】:

    只需将中断保存到一个值并重复使用它们:

    data=c(1,2,3,4,5,6,7,8)
    mn=min(data)
    mx=max(data)
    d=(mx-mn)/3
    br=seq(from=mn,to=mx,by=d)
    mycuts=cut(data,breaks = br, include.lowest=TRUE)
    otherdata=c(4,8)
    cut(otherdata,breaks = br, include.lowest=TRUE)
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2019-08-31
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2012-07-28
      • 1970-01-01
      相关资源
      最近更新 更多