Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Displaying table values by proportion in R

Tags:

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.

For example, if my first row is 2,2,0 I want to make it .5,.5,0

Similarly, if a row is 4,15,1 I want to make it .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.

like image 542
CHN Avatar asked Feb 17 '26 17:02

CHN


2 Answers

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
like image 74
Jota Avatar answered Feb 20 '26 07:02

Jota


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)
like image 36
Gregor Thomas Avatar answered Feb 20 '26 06:02

Gregor Thomas



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!