将值更改为 R 中行的百分比
change value to percentage of row in R
这是我的数据
A B C
A 9 1 0
B 2 2 2
C 3 3 3
我想得到每一行的百分比
我期望的数据是
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 上有列名。
所以实际上我的真实数据是
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
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
的建议
round(prop.table(as.matrix(df1),1),2)
这是我的数据
A B C
A 9 1 0
B 2 2 2
C 3 3 3
我想得到每一行的百分比
我期望的数据是
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 上有列名。 所以实际上我的真实数据是
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
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
的建议round(prop.table(as.matrix(df1),1),2)