如何将一个矩阵的值转换为百分比,而不R中
改变文件格式,我有一个矩阵是res
如何将一个矩阵的值转换为百分比,而不R中
> res [,1] [,2] [,3] [,4] [,5]
[1,] 0.025431667 0.024636307 0.02812685 0.02733088 0.02807624
[2,] -0.005383589 0.000000000 0.02807624 0.02258878 0.02322090
[3,] -0.002674251 -0.002674251 0.05502400 0.00000000 0.01385476
[4,] 0.055024000 0.061028259 0.05932779 0.05956794 0.05839394
[5,] 0.059327790 0.059567938 0.05839394 0.06048811 0.05944368
我希望有结果的百分比,并保持数据结构不变。
当我尝试像percent(res)
从scales
我得到一个向量,而不是一个矩阵
> percent(res) [1] "2.54%" "-0.54%" "-0.27%" "5.50%" "5.93%" "2.46%" "0.00%" "-0.27%"
[9] "6.10%" "5.96%" "2.81%" "2.81%" "5.50%" "5.93%" "5.84%" "2.73%"
[17] "2.26%" "0.00%" "5.96%" "6.05%" "2.81%" "2.32%" "1.39%" "5.84%"
[25] "5.94%"
任何建议吗?
回答:
你可以这样做:
require(scales) set.seed(1) # Just for reproducibility
res <- matrix(data = rnorm(20), nrow = 5, ncol = 4)
> res
[,1] [,2] [,3] [,4]
[1,] -0.6264538 -0.8204684 1.5117812 -0.04493361
[2,] 0.1836433 0.4874291 0.3898432 -0.01619026
[3,] -0.8356286 0.7383247 -0.6212406 0.94383621
[4,] 1.5952808 0.5757814 -2.2146999 0.82122120
[5,] 0.3295078 -0.3053884 1.1249309 0.59390132
res[] <- percent(res)
> res
[,1] [,2] [,3] [,4]
[1,] "-63%" "-82%" "151%" "-4%"
[2,] "18%" "49%" "39%" "-2%"
[3,] "-84%" "74%" "-62%" "94%"
[4,] "160%" "58%" "-221%" "82%"
[5,] "33%" "-31%" "112%" "59%"
回答:
的formmattable包做工精细用矩阵的功能百分比:
library(formattable) percent(res)
,这是结果:
X..1. X..2. X..3. X..4. X..5. [1,] 2.54% 2.46% 2.81% 2.73% 2.81%
[2,] -0.54% 0.00% 2.81% 2.26% 2.32%
[3,] -0.27% -0.27% 5.50% 0.00% 1.39%
[4,] 5.50% 6.10% 5.93% 5.96% 5.84%
[5,] 5.93% 5.96% 5.84% 6.05% 5.94%
回答:
而且也:
require(scales) mat <- matrix(rexp(200, rate=.1), ncol=5, nrow=5)
> mat
[,1] [,2] [,3] [,4] [,5]
[1,] 0.8633327 0.59608 4.255264 4.9075876 14.690223
[2,] 13.3531120 33.97510 9.292887 9.2030803 8.963202
[3,] 10.9540116 13.00999 3.345536 12.0012241 16.985236
[4,] 8.7139062 40.25450 22.578629 0.7283414 1.389453
[5,] 15.0364007 11.74895 8.764188 13.8024305 9.303271
> res <- apply(mat, 2, function(x) percent(x/100))
> res
[,1] [,2] [,3] [,4] [,5]
[1,] "0.9%" "0.6%" "4.3%" "4.9%" "14.7%"
[2,] "13.4%" "34.0%" "9.3%" "9.2%" "9.0%"
[3,] "11.0%" "13.0%" "3.3%" "12.0%" "17.0%"
[4,] "8.7%" "40.3%" "22.6%" "0.7%" "1.4%"
[5,] "15.0%" "11.7%" "8.8%" "13.8%" "9.3%"
> res <- apply(mat, 2, function(x) percent(x)) #or without '/100' if you want 9% instead of 0.9%
以上是 如何将一个矩阵的值转换为百分比,而不R中 的全部内容, 来源链接: utcz.com/qa/263572.html