简体   繁体   English

如何将格式更改为矩阵列表中的百分比

[英]How do change the format to percent in a list of matrices

I have a list of matrices, where i want to change the values in the matrices to percent. 我有一个矩阵列表,我想将矩阵中的值更改为百分比。

The matrices in the list look like this 列表中的矩阵如下所示

       [,1]     [,2]        [,3]        [,4]        [,5]        [,6]        [,7]        [,8]        [,9]       
Year     ""    "2010"      "2011"      "2012"      "2013"      "2014"      "2015"      "2016"      "2017"     
Women "Women"  "0.4521919" "0.4360186" "0.4344594" "0.4314785" "0.4363432" "0.4402187" "0.4437688" "0.4414514"
Men    "Men"   "0.5478081" "0.5639814" "0.5655406" "0.5685215" "0.5636568" "0.5597813" "0.5562312" "0.5585486"

Which I want to convert into 我想转换成

       [,1]     [,2]        [,3]        [,4]        [,5]        [,6]        [,7]        [,8]        [,9]       
Year     ""    "2010"      "2011"      "2012"      "2013"      "2014"      "2015"      "2016"      "2017"     
Women "Women"  "45.21919%" "43.60186%" "43.44594%" "43.14785%" "43.63432%" "44.02187%" "44.37688%" "44.14514%"
Men    "Men"   "54.78081%" "56.39814%" "56.55406%" "56.85215%" "56.36568%" "55.97813%" "55.62312%" "55.85486%"

I've tried to do this using lapply 我试图用lapply做到这lapply

x <- lapply(df, function(x) percent(as.numeric(x[2:nrow(x),(3:ncol(x))])))

But this returns one vector of characters rather than two rows which then could be returned to the desired format with cbind . 但这会返回一个字符向量,而不是两行,然后可以使用cbind返回所需的格式。 The values being characters isn't really an issue, but numeric values would be prefered. 作为字符的值并不是真正的问题,但最好使用数字值。

Does anyone have a suggestion on how to make a nice solution to the problem above. 是否有人对如何解决上述问题提出建议。 Grateful for all tips! 感谢所有提示!

/J / J

A matrix can only hold one data type. 矩阵只能保存一种数据类型。 Transform each matrix to a data.frame using as.data.frame() in order to be able to have different data types in a same data structure. 使用as.data.frame()将每个矩阵转换为data.frame,以便在同一数据结构中具有不同的数据类型。 You could also remove the first column of each matrix, which should work as well since it seems it is the only character value in your data structure. 您也可以删除每个矩阵的第一列,因为它似乎是数据结构中唯一的character值,所以它也应该工作。

While I would use data.frame instead of a matrix, but this may depend on what your end goal is. 尽管我将使用data.frame而不是矩阵,但这可能取决于您的最终目标。 You could subset the matrix and append a % sign. 您可以对矩阵进行子集化并附加一个%符号。

xy <- matrix(runif(9), nrow = 3)
xy[, 1] <- c("", "men", "women")
xy[1, ] <- c("", "2010", "2011")
xy[-1, -1] <- paste(as.numeric(xy[-1, -1]) * 100, "%")

xy
     [,1]    [,2]                 [,3]                
[1,] ""      "2010"               "2011"              
[2,] "men"   "85.1143697509542 %" "11.8173067457974 %"
[3,] "women" "89.0305595472455 %" "64.4668221008033 %"

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM