Reputation: 175
I have a table:
X1 X2 X3
Y1 10 12 15
Y2 45 5 23
Y3 12 47 56
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..
Upvotes: 0
Views: 120
Reputation: 887128
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
or
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%
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,"%")
or
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%
Upvotes: 1