在R中以相等间隔计算数据集中总百分比
我正在制作一个数据集,其中包含每个快速消费品类别的总量及其在各主要渠道的销售分布,如列中所示。摘录如下在R中以相等间隔计算数据集中总百分比,r,percentage,calculated-columns,R,Percentage,Calculated Columns,我正在制作一个数据集,其中包含每个快速消费品类别的总量及其在各主要渠道的销售分布,如列中所示。摘录如下 CTY totsal MTsal GTsal Othsal totsal MTsal GTsal Othsal food food food food deo deo deo deo Arg 47313 19620 15052 12641 178 113 41 24 Au
CTY totsal MTsal GTsal Othsal totsal MTsal GTsal Othsal
food food food food deo deo deo deo
Arg 47313 19620 15052 12641 178 113 41 24
Aus 143140 85172 4634 53334 459 438 5 16
Bel 125399 82966 7818 34614 424 229 5 190
在我的输出数据集中,我想计算每第四列中总类别组的份额,例如totsal food和totsal deo。因此,这些频道的份额必须是1,频道的份额加起来必须是它们各自的值。我看到的示例输出是:
CTY totshar MTshar GTshar Othshar totshar MTshar GTshar Othshar
food food food food deo deo deo deo
Arg 1 0.4 0.3 0.3 1.0 0.6 0.2 0.1
Aus 1 0.6 0.0 0.4 1.0 1.0 0.0 0.0
Bel 1 0.7 0.1 0.3 1.0 0.5 0.0 0.4
上面的例子是一个摘录,我需要加入灵活性,以包括尽可能多的类别和国家。您可以这样做。 首先,我复制并粘贴了您的数据:
d <- read.table("clipboard",header=T)
d
CTY totsal MTsal GTsal Othsal totsal.1 MTsal.1 GTsal.1 Othsal.1
1 <NA> food food food food deo deo deo deo
2 Arg 47313 19620 15052 12641 178 113 41 24
3 Aus 143140 85172 4634 53334 459 438 5 16
4 Bel 125399 82966 7818 34614 424 229 5 190
我使用sapply
计算每组的百分比,并使用矩阵
函数转换结果。sappy函数“循环”通过grep
搜索找到的所有组。在函数(x,y,z)
中,它将属于该组的所有列子集化。这里是第一个m[,gr==gr\u total[1]]
。因为R针对矢量化过程进行了优化,所以可以将向量/矩阵除以向量。尝试m[,gr==gr_total[1]]/m[,gr_total[1]]
。有关matrix()
函数,请参见?matrix
,并检查sapply
输出
matrix(sapply(gr_total, function(x, y, z) z[, y==x]/z[, x], gr, m), nrow(m), ncol(m), byrow = FALSE)
[,1] [,2] [,3] [,4] [,5] [,6] [,7] [,8]
[1,] 1 0.4146852 0.31813666 0.2671782 1 0.6348315 0.23033708 0.13483146
[2,] 1 0.5950258 0.03237390 0.3726003 1 0.9542484 0.01089325 0.03485839
[3,] 1 0.6616161 0.06234499 0.2760309 1 0.5400943 0.01179245 0.44811321
您可以使用舍入
功能将一位数字舍入。假设您将结果保存在m1
中,请使用round(m1,1)
。
Colnames可以替换为
Colnames(m1)您可以发布数据帧的摘录吗?(只是dput(head(df))
)我不知道你的意思。我展示的示例是一个摘录。这里有8列,其中第1列是第2列3 4的总计,第5列是第6列7 8的总计。整个数据集的这一进程将继续完美地工作。你能详细解释一下最后的Sappy和matrix代码吗?此外,我也不会将列名作为原始数据集。我把它们作为V1 V2等,有没有办法把它们取回或用原始列名替换这些V1 V2?
gr_total <- grep("tot", colnames(d)[-1])
gr <- sort(rep(gr_total, 4))
matrix(sapply(gr_total, function(x, y, z) z[, y==x]/z[, x], gr, m), nrow(m), ncol(m), byrow = FALSE)
[,1] [,2] [,3] [,4] [,5] [,6] [,7] [,8]
[1,] 1 0.4146852 0.31813666 0.2671782 1 0.6348315 0.23033708 0.13483146
[2,] 1 0.5950258 0.03237390 0.3726003 1 0.9542484 0.01089325 0.03485839
[3,] 1 0.6616161 0.06234499 0.2760309 1 0.5400943 0.01179245 0.44811321