我如何为每一行计算总和并在每个值附近写出该总和的百分比 [英] How can I for each row calculate the sum and write the percentage of that sum near each value

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

问题描述

我有一张桌子:

   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%

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

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆