r - R expss 包:按统计格式化数字/将不同的格式应用于交替行
问题描述
我正在探索 expss 包,以便为 R 完全更改 SPSS。我的标准表格在行中显示计数和百分比,有时还补充了其他统计信息。
有没有办法通过统计或行来改变数字格式?更具体地说,我想用 0 位数字显示计数,用 2 位数字显示百分比,理想情况下以 % 格式显示,用 2 位数字显示平均值。
我在 htmlTables 和 htmlTable.etable {expss} 中进行了搜索,但无法找到执行此操作的方法。
发送所有帮助
嗨,格雷戈里,
Tx 为您的利益。请参见下面的小示例。
德克萨斯州,米查
解决方案
表格是通常的 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()
推荐阅读
- http - 为获取的文件设置 MIME 类型
- python - 带有应用程序的 Django
- audiounit - OSX 14:识别莫哈韦麦克风缺少权限
- django - Django 2:类的未解析属性引用“get_queryset”
- macos - nodemon:找不到命令
- c# - ASP.NET:ItemTemplate 中 2 个差异值的条件逻辑
- java - 如何使用长按释放手势检测轻按和长按的手势
- python - 文本分类 + 朴素贝叶斯 + Python:输入包含 NaN、无穷大或对于 dtype('float64') 来说太大的值
- kubernetes - 如何让不同节点上的 pod 到 pod ping 正常工作?
- python - 我很难在 Spyder (Python 3.6) 中获得完整的输出列表