[英]Append a totals row and/or column to a data.frame in R
Previously, I have used the addorn_totals
function from the janitor
package to add row and columns totals to a data.frame.以前,我使用
janitor
package 的addorn_totals
function 将行和列总计添加到 data.frame。 The content of the data.frame was count, so that was fine: data.frame 的内容是计数的,所以很好:
RegionSize
size KUALA LUMPUR OTHERS PENANG SELANGOR DARUL EHSAN TOTAL
tiny 20 3 1 0 24
small 164 120 20 90 394
medium 100 69 0 0 169
big 0 293 106 0 399
TOTAL 284 485 127 90 986
Now I am working on a data.frame, where each cell is a proportion.现在我正在研究一个data.frame,其中每个单元格都是一个比例。 I need to have the total row and also column, but the
addorn_totals
cannot be used in that case, because the order of operations return wrong values.我需要总行和列,但在这种情况下不能使用
addorn_totals
,因为操作的顺序返回错误的值。
So I have three separate tables:所以我有三个单独的表:
Summary
size KUALA LUMPUR OTHERS PENANG SELANGOR DARUL EHSAN
1 tiny 0.000 0.000 0.000 0.000
2 small 435.344 245.598 333.317 272.342
3 medium 187.874 9656.649 0.000 0.000
4 big 0.000 116.861 138.366 0.000
RegionTotals
experience region1
1: 156.523 PENANG
2: 272.342 SELANGOR DARUL EHSAN
3: 343.998 KUALA LUMPUR
4: 296.601 OTHERS
SizeTotals
experience size
1: 0.000 tiny
2: 348.692 small
3: 136.207 big
4: 223.415 medium
overallTotal
experience
1: 276.613
How can i achieve the following result, considering that the regions and sizes may change?考虑到区域和大小可能会发生变化,我怎样才能达到以下结果? For example sometimes i will not have the region "OTHERS" or the size "BIG" depending on the data that i get.
例如,有时我不会有区域“其他”或大小“大”,具体取决于我获得的数据。 How can I achieve this:
我怎样才能做到这一点:
Summary
size KUALA LUMPUR OTHERS PENANG SELANGOR DARUL EHSAN TOTAL
1 tiny 0.000 0.000 0.000 0.000 0.000
2 small 435.344 245.598 333.317 272.342 348.692
3 medium 187.874 9656.649 0.000 0.000 223.415
4 big 0.000 116.861 138.366 0.000 136.207
5. TOTAL 343.998 296.601 156.523 272.342 276.613
You can use rbind to add a row to your data frame, eg:您可以使用rbind在数据框中添加一行,例如:
total <- c(size="TOTAL", apply(x[,-1], FUN=sum, MAR=2)
rbind(x, total)
In the same way, you can use cbind to add a column.同样,您可以使用cbind添加列。 The only tricky part is that you must omit the non-numeric columns from the summation: that's why I use the index -1, which removes the first column.
唯一棘手的部分是您必须从求和中省略非数字列:这就是我使用索引 -1 的原因,它删除了第一列。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.