我有一个数据框 . 我想创建一个频率表,用“组”显示bin频率 . 如果有一个包含0个实体的bin,我希望它显示该bin中有0个实体 .
如果我使用 table()
函数,我会得到数据帧中所有二进制数的频率计数,但不是"Group" . 它也没有告诉我,例如,我在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
有任何想法吗?
1 回答
不是
table
做你想要的第一个问题:它显示了bin 3,group 2的
0
条目(我认为这就是你的意思,组1中的bin 3有行) . 此外,通过设置因子级别,我也能够显示bin_index 1 . 对于第二个问题,只需使用melt
: