【问题标题】:Frequency Count for All Possible Bins所有可能分档的频率计数
【发布时间】:2014-02-03 21:30:59
【问题描述】:

我有一个数据框。我想要创建一个频率表,按“组”显示 bin 频率。如果有一个包含 0 个实体的 bin,我希望它显示该 bin 中有 0 个实体。

如果我使用table() 函数,我会获得数据框中所有 bin 的频率计数,但不是按“组”。它也没有告诉我,例如,我在 Group 1 Bin 3 中没有任何行。我也查看了tabulate(),但这似乎也不是我所需要的。不知何故,我需要告诉它可能的垃圾箱集合实际上是什么。

这是一些示例代码。

    df = as.data.frame(rbind(c(1,1.2), c(1,1.4), c(1,2.1), c(1,2.5), c(1,2.7), c(1,4.1), c(2,1.6), c(2,4.5), c(2,4.3), c(2,4.8), c(2,4.9)))
    colnames(df) = c("Group", "Value")
    df.in = split(df, df$Group)

    FindBin = function(df){
      maxbin = max(ceiling(df$Value),na.rm=TRUE)+1 #what is the maximum bin value. 
       bin = seq(from=0, to=maxbin, by=1) #Specify your bins: 0 to the maximum value by increments of 1
       df$bin_index = findInterval(df$Value, bin, all.inside = TRUE) #Determine which bin the value is in 
      return(df)
    }

    df.out = lapply(names(df.in), function(x) FindBin(df.in[[x]]))
    df.out2 = do.call(rbind.data.frame, df.out) #Row bind the list of dataframes to one dataframe

df.out2 的输出如下所示:

        Group Value bin_index
    1      1   1.2         2
    2      1   1.4         2
    3      1   2.1         3
    4      1   2.5         3
    5      1   2.7         3
    6      1   4.1         5
    7      2   1.6         2
    8      2   4.5         5
    9      2   4.3         5
    10     2   4.8         5
    11     2   4.9         5

除了上面的输出,我想要一个结果的摘要输出,看起来像这样:

    Group     Bin     Freq
    1         1       0
    1         2       2
    1         3       3
    1         4       0
    1         5       1
    2         1       0
    2         2       1
    2         3       0
    2         4       0
    2         5       4

有什么想法吗?

【问题讨论】:

  • 无关,你为什么不直接使用df$bin_index <- ceiling(df$Value)

标签: r frequency


【解决方案1】:

table 不会为你的第一个问题做你想做的事:

df$bin_index <- factor(df$bin_index, levels=1:5)
table(df[, c("Group", "bin_index")])
#       bin_index
# Group 1 2 3 4 5
#     1 0 2 3 0 1
#     2 0 1 0 0 4

它显示了 bin 3 第 2 组的 0 条目(我想这就是您的意思,第 1 组中有 bin 3 的行)。此外,通过设置因子水平,我还能够让 bin_index 1 显示出来。对于第二个问题,请使用melt

library(reshape2)
melt(table(df[, c("Group", "bin_index")]))
#    Group bin_index value
# 1      1         1     0
# 2      2         1     0
# 3      1         2     2
# 4      2         2     1
# 5      1         3     3
# 6      2         3     0
# 7      1         4     0
# 8      2         4     0
# 9      1         5     1
# 10     2         5     4    

【讨论】:

  • 谢谢,这在很大程度上完成了我需要它做的事情,让我比以前走得更远。使用因子然后使用表是一个好主意。我所有的组都有不同数量的 bin_indexes。例如,第 1 组的 bin 可能高达 130,而第 2 组的 bin 可能高达 105,等等。也许我可以按组号删除 bin_index 大于该组的最大 bin_index 的行。谢谢!
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2023-03-08
  • 1970-01-01
  • 2020-10-20
  • 1970-01-01
相关资源
最近更新 更多