格式化R中的百分比表 [英] Format table of percentages in R

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

问题描述

我想要一张百分比表,将值格式化为百分比,并以一种不错的格式显示它们.我正在使用RStudio并将其编织为PDF.

I want to take a table of percentages, format the values as percentages and display them in a nice format. I'm using RStudio and knitting to PDF if that matters.

我还看过其他有关此的帖子,但是它们似乎都不干净,效果也不佳.

I have seen other posts about this, but none of them seem clean, and don't really work well.

例如,下面的apply语句的格式为百分比,但是,它去除了年份,并用引号将表引起来.我可以使用kable来固定引号,但似乎这是一个非常普遍的问题,为此有一个包装或技巧.

For instance, the apply statement below does format as percent, however, it strips the years off, and surrounds the table in quotes. I can fix the quotes by using kable, but it just seems like this is a common enough problem that there is a package or trick for this.

任何帮助将不胜感激.

myTable <- structure(c(.20, .10, .25, .10, 
                       .20, .10, .25, .20, 
                       .20, .10, .25, .30, 
                       .20, .10, .25, .40, 
                       .20, .60, .25, .0), 
            class = "table", 
            .Dim = c(5L, 4L), 
            .Dimnames = structure(list(c("2006", "2007", "2008", "2009", "2010"), 
                                       c("1", "2", "3", "4")), 
                                  .Names = c("", "")))

# Table is fine, but needs decimal shifted and % sign added
myTable

formattedTable <- apply(myTable*100, 2, function(u) sprintf("%.0f%%", u))

# Decimal is shifted and % sign added, but no years, and quotes around text
formattedTable

# Fixes the quotes issue, still no years
kable(formattedTable)

推荐答案

您可以使用表中的属性创建一个新矩阵,然后强制转换为data.frame.无需apply()循环.

You could create a new matrix using the attributes from the table, then coerce to data.frame. No apply() looping necessary.

as.data.frame(matrix(
    sprintf("%.0f%%", myTable*100), 
    nrow(myTable), 
    dimnames = dimnames(myTable)
))
#        1   2   3   4
# 2006 20% 10% 25% 40%
# 2007 10% 25% 30% 20%
# 2008 25% 20% 20% 60%
# 2009 10% 20% 10% 25%
# 2010 20% 10% 25%  0%

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

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