Change the value to the percentage of the row in R

this is my data

ABC A 9 1 0 B 2 2 2 C 3 3 3 

I want to get a percentage of each row

my waiting data

  ABC A 0.9 0.1 0 B 0.33 0.33 0.33 C 0.33 0.33 0.33 

I made my data with "dcast", and there is a column name on A, B and C. Therefore, actually my real data

  Name ABC 1 A 0.9 0.1 0 2 B 0.33 0.33 0.33 3 C 0.33 0.33 0.33 
+6
source share
1 answer

Seems like a fair example for

 df/rowSums(df) # ABC # A 0.9000000 0.1000000 0.0000000 # B 0.3333333 0.3333333 0.3333333 # C 0.3333333 0.3333333 0.3333333 

If you do not want so many digits after dialing options(digits = 2) either use print(df/rowSums(df), digits = 2) or use round

 round(df/rowSums(df), 2) # ABC # A 0.90 0.10 0.00 # B 0.33 0.33 0.33 # C 0.33 0.33 0.33 

Or as suggested by @akrun

 round(prop.table(as.matrix(df1),1),2) 
+11
source

All Articles