【发布时间】: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)?