r - 表格格式 - 数字、小数、百分比
问题描述
我需要在 5%,10% 之类的值以及均值和 sd 的十进制值之后显示 % 符号
library(expss)
xltable=EDat %>% calc(list(
cro_cpct (A1A,total())
cro_mean_sd_n (N_A1A, total())
))
xltable
我期待 A1A 的百分比符号表和 N_A1A 的小数位表
解决方案
您可以使用 设置所需的小数位数expss_digits
。百分比格式化功能:
########################
add_percent = function(x, digits = get_expss_digits(), ...){
UseMethod("add_percent")
}
add_percent.default = function(x, digits = get_expss_digits(), ...){
res = formatC(x, digits = digits, format = "f")
nas = is.na(x)
res[nas] = ""
res[!nas] = paste0(res[!nas], "%")
res
}
add_percent.etable = function(x, digits = get_expss_digits(), excluded_rows = "#", ...){
included_rows = !grepl(excluded_rows, x[[1]], perl = TRUE)
for(i in seq_along(x)[-1]){
if(!is.character(x[[i]])){
x[[i]][included_rows ] = add_percent(x[[i]][included_rows])
}
}
x
}
######################
library(expss)
data(mtcars)
mtcars = apply_labels(mtcars,
mpg = "Miles/(US) gallon|Mean",
cyl = "Number of cylinders",
disp = "Displacement (cu.in.)|Mean",
hp = "Gross horsepower|Mean",
drat = "Rear axle ratio",
wt = "Weight (lb/1000)",
qsec = "1/4 mile time|Mean",
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"
)
mtcars_table = cro_cpct(list(mtcars$cyl),
list(mtcars$vs %nest% mtcars$am, "#Total"))
add_percent(mtcars_table)
# | | | Engine | | | | #Total |
# | | | V-engine | | Straight engine | | |
# | | | Transmission | | Transmission | | |
# | | | Automatic | Manual | Automatic | Manual | |
# | ------------------- | ------------ | ------------ | ------ | --------------- | ------ | ------ |
# | Number of cylinders | 4 | | 16.7% | 42.9% | 100.0% | 34.4% |
# | | 6 | | 50.0% | 57.1% | | 21.9% |
# | | 8 | 100.0% | 33.3% | | | 43.8% |
# | | #Total cases | 12 | 6 | 7 | 7 | 32 |
推荐阅读
- laravel - 具有多个日期过滤器的 Laravel 集合,带有 or 运算符
- c# - Finding minimum and maximum from array in C#
- ios - Custom UIbutton default color Xcode Swift
- c# - ReactiveUI ObservableAsPropertyHelper 与正常的后备变量
- php - 使用 PHP mysql 显示阿拉伯语数据时出错
- postgresql - 使用 group by、2 和 where 子句连接 4 个表
- python - 底图散点图(Matplotlib) - 错误无法设置属性
- r - 安装 r 包时如何解决此错误?
- java - Java Swing JTextArea 和 BufferedReader
- c++ - 包括 Boost ASIO 与 Amazon Gamelift SDK 的冲突