【问题标题】:How to change discrete ratio data into ordinal data in R?如何将离散比率数据更改为R中的序数数据?
【发布时间】:2011-10-19 09:08:50
【问题描述】:

这是一个例子:

   height
1  1.5
2  1.3 
3  1.9 
4  1.5
5  1.6 

其中有 1000 个,高度从 0 到 1.9。我想把它们分成3个级别:低、中、高。那么它们就是序数数据。

结果应该是这样的:

   height
1  medium
2  low
3  high
4  medium
5  medium

摘要应如下所示:

        height
low:    203
medium: 723
high:   74

我尝试使用循环,但“低、中、高”是字符,而不是级别。 下面是我做低级部分的方法:

height_cuts = c(1.5,1.9)
for(i in 1:nrow(health.sample)){
  if(is.na(health.sample$height[i])==FALSE){
    if(health.sample$height[i] < height_cuts[1]){
      health.sample$height[i] = low_h
    }
  }
}

【问题讨论】:

  • 你还没有说最重要的——应该如何定义这些类别

标签: r


【解决方案1】:
cut(height, quantile(height, prob=c(203, 723, 74)/1000 ), labels=c("low", "medium", "high") )

【讨论】:

  • +1 用于使用 OP 的摘要示例代替最重要的信息,OP 在问题中遗漏了这些信息 :-)
【解决方案2】:

cut 会很方便地剪切您的数据。

# cut needs all endpoints explicitly specified, including outside bounds
height_cuts <- c(-Inf, 1.5, 1.9, Inf)

hcut <- cut(height, height_cuts, labels=c("low", "medium", "high"))

ETA:这将使间隔基于 right=FALSE:

hcut <- cut(height, height_cuts, right=FALSE, ...)

【讨论】:

    【解决方案3】:

    使用cut:

    cut(x$height, c(0,1.5,1.9,10), labels=c("low","med","high"), right=FALSE)
    # [1] med  low  high med  med
    

    【讨论】:

      猜你喜欢
      • 2021-06-29
      • 2018-02-13
      • 2020-06-13
      • 2011-10-24
      • 1970-01-01
      • 1970-01-01
      • 2018-08-14
      • 2020-04-30
      • 1970-01-01
      相关资源
      最近更新 更多