【问题标题】:Grouping numeric values into categories in R?将数值分组到R中的类别?
【发布时间】:2023-04-09 19:20:01
【问题描述】:

我有一个变量表示工业部门的值在 1-100 之间;这些扇区可以不定期地分为 20 个宏观扇区(例如 1-5 -> 扇区_1、6-12 -> 扇区_2...)。

在第二个变量中转换第一个变量最有效的方法是什么?

我正在考虑使用如下函数,但解决方案效率不高,而且有点难看:

index <- function(x) {
  if (x<= 5){
    x <- "Sector_1"
  }
  if (x>5 & x<=12){
    x <- "Sector_3"
  }
return(x)
}

【问题讨论】:

  • 我建议cut,例如cut(x, c(-Inf, 5, 12, Inf), labels=c("Sector_1", "Sector_3", "Sector_n"))
  • findInterval。另见this
  • `Cut' 效果很好!

标签: r function dataframe variables grouping


【解决方案1】:

按照@r2evans 的建议,使用cut。这是您问题上下文中可重现的示例:

set.seed(1) #make results reproducible. 
sector <- data.frame(mini.sector = seq(1,10,1), value = round(runif(10, 1, 100), 0))

#name macro sectors as 'a', 'b', 'c' and 'n' and assign them to micro sectors based on defined value cuts.
sector$macro.sector <- cut(sector$value, c(-Inf, 10, 25, 50, Inf), labels=c("a", "b", "c", "n"))

head(sector) #show first five row from data frame 'sector'.

mini.sector  value  macro.sector
          1     27             c
          2     38             c
          3     58             n
          4     91             n
          5     21             b
          6     90             n

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2021-07-15
    • 2022-09-30
    • 1970-01-01
    • 2020-07-01
    • 1970-01-01
    • 2018-06-23
    • 2019-10-31
    • 2022-01-18
    相关资源
    最近更新 更多