change value to percentage of row in R [duplicate]

五迷三道 提交于 2019-11-27 07:44:46

问题


This question already has an answer here:

  • Calculate row-wise proportions 4 answers

this is my data

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

I want to get percentage of each row

my expect data is

     A    B    C
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 column name on A,B and C. so actually my real data is

  Name    A    B    C
1    A  0.9  0.1    0 
2    B 0.33 0.33 0.33
3    C 0.33 0.33 0.33

回答1:


Seems a fair case for

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

If you don't want so many digits after the dot set options(digits = 2) or use print(df/rowSums(df), digits = 2) or use round

round(df/rowSums(df), 2)
#      A    B    C
# 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)


来源:https://stackoverflow.com/questions/31638003/change-value-to-percentage-of-row-in-r

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!