将值更改为 R 中行的百分比 [英] change value to percentage of row in R

查看:53
本文介绍了将值更改为 R 中行的百分比的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

这是我的数据

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

我想获得每一行的百分比

I want to get percentage of each row

我期望的数据是

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

我用dcast"制作了数据,A、B 和 C 上有列名.所以实际上我的真实数据是

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

推荐答案

对于

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

如果您不想在点集后设置这么多数字 options(digits = 2) 或使用 print(df/rowSums(df), digits = 2)> 或使用 round

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

或者按照@akrun 的建议

Or as suggested by @akrun

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

这篇关于将值更改为 R 中行的百分比的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆