řexpss包:通过统计格式的数字/应用不同的格式,以交替的行

问题描述 投票:2回答:1

我探索expss包才能彻底改变SPSS对R.我的标准tabels显示计数和百分比在行,有时还辅以其他统计资料。

有没有办法通过统计或行更改数字格式?更具体的我想和0位,2位和百分比最好是在%格式,并与2位数字的手段来显示计数。

我搜索在HTML表格和HTML Table.editable {}表达,但我无法找到一个方法来做到这一点。

TX的所有帮助

嗨格雷戈里

TX的关注。请参见下面的小例子。

Table as is

Table I'd like to see

TX,米莎

r html-table formatting expss
1个回答
1
投票

表是平常data.frames,所以我们可以很容易地应用标准的R格式化功能。例:

library(expss)
data(mtcars)
mtcars = apply_labels(mtcars,
                      mpg = "Miles/(US) gallon",
                      cyl = "Number of cylinders",
                      disp = "Displacement (cu.in.)",
                      hp = "Gross horsepower",
                      drat = "Rear axle ratio",
                      wt = "Weight (1000 lbs)",
                      qsec = "1/4 mile time",
                      vs = "Engine",
                      vs = c("V-engine" = 0,
                             "Straight engine" = 1),
                      am = "Transmission",
                      am = c("Automatic" = 0,
                             "Manual"=1),
                      gear = "Number of forward gears",
                      carb = "Number of carburetors"
)


# custom formating function
custom_format = function(tbl, percent_digits = 2, count_digits = 0){
    percent_rows = grepl("\\|%$", tbl[[1]], perl = TRUE) # get rows with percent format
    count_rows = grepl("\\|N$", tbl[[1]], perl = TRUE) # get rows with count format
    # format each stat
    rounded_percent = format(tbl[percent_rows,-1], digits = percent_digits, nsmall = percent_digits) 
    rounded_count = format(tbl[count_rows,-1], digits = count_digits, nsmall = count_digits)
    # replcae data in orginal tables with formatted stat
    tbl[percent_rows,-1] = rounded_percent
    tbl[count_rows,-1] = rounded_count
    ##### remove NA which arise during formatting
    recode(tbl) = perl("^\\s*NA\\s*$") ~ ""
    tbl
}


## example
expss_output_viewer()
mtcars %>% 
    tab_cells(gear) %>% 
    tab_cols(total(), am) %>% 
    tab_stat_cases(label = "N", total_row_position = "above") %>% 
    tab_stat_cpct(label = "%", total_row_position = "none") %>% 
    tab_pivot(stat_position = "inside_rows") %>% 
    custom_format()

enter image description here

© www.soinside.com 2019 - 2024. All rights reserved.