[英]Displaying table values by proportion in R
I have a table in R , and I would like to change each row so that the numbers come up proportionally as opposed to the total quantity. 我在R中有一个表,我想更改每一行,以便数字按比例增加,而不是总数量。
For example, if my first row is 2,2,0 I want to make it .5,.5,0 例如,如果我的第一行是2,2,0我想要它.5,.5,0
Similarly, if a row is 4,15,1 I want to make it .2,.75,.05 同样,如果一行是4,15,1我想要它.2,.75,。05
Is there a way to do this to the entire table at once? 有没有办法一次对整个表格执行此操作? I know this is probably pretty easy but I've been working on it for a long time.
我知道这可能很容易,但我已经做了很长时间了。
You can try this: 你可以试试这个:
# sample data
a <- rbind(c(2,2,0), c(4,15,1))
# solution
a / apply(a, 1, sum)
# [,1] [,2] [,3]
#b 0.5 0.50 0.00
#a 0.2 0.75 0.05
If your data is a matrix, 如果您的数据是矩阵,
my_data = matrix(rpois(12, lambda = 5), nrow = 4)
then this is one way to do it: 那么这是一种方法:
my_data / rowSums(my_data)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.