本文介绍了如何为每一行计算总和并在每个值附近写出总和的百分比的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一张桌子:

   X1 X2 X3

Y1 10 12 15
Y2 45 5  23
Y3 12 47 56

如何为每一行计算求和并在每个值附近写出该总和的百分比。
例如:
X1%X2%X3%

How can I for each row calculate the sum and write the percentage of that sum near each value.For example: X1 percent X2 percent X3 percent

Y1 10  27%    12   32%   15 40.5%
Y2 45   ..    5     ..   23..
Y3 12    ..   47    ..   56..


推荐答案

您可以使用。如果 dat 是数据集(在此示例中, dat 是data.frame)

You could either use. If dat is the dataset (dat is data.frame in this example)

 v1 <- paste0(round(prop.table(as.matrix(dat),margin=1),2)*100,"%") #suggested by @Ananda Mahto

 v2 <- matrix(paste0(100*round(as.matrix(dat)/rowSums(dat),2),"%"),3,3)
 cbind(dat, v1)[c(rbind(1:3,4:6))]
 #    X1   1 X2   2 X3   3
 # Y1 10 27% 12 32% 15 41%
 # Y2 45 62%  5  7% 23 32%
 # Y3 12 10% 47 41% 56 49%



更新



对于5行4列,步骤相同。例如:

Update

For, 5 rows and 4 columns, the steps are the same. For example:

 set.seed(42)
 dat1 <- as.data.frame(matrix(sample(5:70, 5*4,replace=T),ncol=4))
 v1 <- paste0(round(prop.table(as.matrix(dat1),margin=1),2)*100,"%") 

 v2 <- matrix(paste0(100*round(as.matrix(dat1)/rowSums(dat1),2),"%"),nrow=5,ncol=4)
 n <- ncol(dat1) 
 cbind(dat1,v2)[c(rbind(1:n,(n+1):(n*2)))]
 #     V1   1 V2   2 V3   3 V4   4
 #   1 65 32% 39 19% 35 17% 67 33%
 #   2 66 28% 53 22% 52 22% 69 29%
 #   3 23 20% 13 11% 66 58% 12 11%
 #   4 59 36% 48 29% 21 13% 36 22%
 #   5 47 27% 51 29% 35 20% 41 24%

这篇关于如何为每一行计算总和并在每个值附近写出总和的百分比的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

10-18 21:10