简体   繁体   中英

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

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 . 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

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. 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.

While I would use data.frame instead of a matrix, but this may depend on what your end goal is. 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 %"

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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