简体   繁体   English

格式化R-package openxlsx中的百分比

[英]Formatting percentages in R-package openxlsx

R3.2.3/openxlsx 3.0.0 R3.2.3 / openxlsx 3.0.0

I have several dataframes that I'm writing to an Excel-workbook with openxlsx. 我有几个数据帧,我正在用openxlsx写入Excel工作簿。 One of the dataframes contains values such as 0.07. 其中一个数据帧包含诸如0.07之类的值。 With

createStyle(numFmt='PERCENTAGE') 

I get 7.00% as output in the workbook. 我在工作簿中得到7.00%的输出。 So far so good. 到现在为止还挺好。 But I want 7% as output. 但我想要7%作为输出。 I've tried several things, such as stacking styles, 我尝试了几件事,比如堆叠样式,

createStyle(numFmt=c('PERCENTAGE','0'))

createStyle(numFmt='PERCENTAGE 0')

but they either result in errors or give unwanted results. 但它们要么导致错误,要么产生不必要的结果。 Any suggestion in the right direction would be most welcome. 任何正确方向的建议都会受到欢迎。 Upgrading to a newer version of openxlsx is not an option. 升级到较新版本的openxlsx不是一种选择。

You can create a percent style with no decimal places using Excel's formatting codes and then apply the style to specific cells. 您可以使用Excel的格式代码创建没有小数位的百分比样式,然后将样式应用于特定单元格。 For example: 例如:

library(openxlsx)

# Fake data
set.seed(2)
dat = data.frame(v1=LETTERS[1:10], v2=runif(10), v3=letters[1:10], v4=runif(10))

# Create an Excel workbook object and add a worksheet
wb = createWorkbook()
sht = addWorksheet(wb, "Data")

# Create a percent style
pct = createStyle(numFmt="0%")

# Add fake data to the worksheet we just created
writeData(wb, sht, dat)

# Add the percent style to the desired cells
addStyle(wb, sht, style=pct, cols=c(2,4), rows=2:(nrow(dat)+1), gridExpand=TRUE)

saveWorkbook(wb, "my_workbook.xlsx")

An advantage of using Excel's percent format is that the underlying data in the spreadsheet will still be numeric, rather than, say, text strings. 使用Excel百分比格式的一个优点是电子表格中的基础数据仍然是数字,而不是文本字符串。

Here's what the worksheet looks like: 这是工作表的样子:

在此输入图像描述

Extending from @parL's answer. 延伸@ parL的答案。 For this approach to work, you need to remove createStyle(numFmt='PERCENTAGE 0') : 要使这种方法起作用,您需要删除createStyle(numFmt='PERCENTAGE 0')

You can try to do something like this: 您可以尝试执行以下操作:

i<-sapply(df, is.numeric)
df[i]<-lapply(df[i], scales::percent)

This makes all numeric value columns in the data frame to string format. 这会使数据框中的所有数值列成为字符串格式。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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