Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Formatting percentages in R-package openxlsx

R3.2.3/openxlsx 3.0.0

I have several dataframes that I'm writing to an Excel-workbook with openxlsx. One of the dataframes contains values such as 0.07. With

createStyle(numFmt='PERCENTAGE') 

I get 7.00% as output in the workbook. So far so good. But I want 7% as output. 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.

like image 951
Jack Random Avatar asked Jan 02 '18 14:01

Jack Random


1 Answers

You can create a percent style with no decimal places using Excel's formatting codes and then apply the style to specific cells. 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.

Here's what the worksheet looks like:

enter image description here

like image 88
eipi10 Avatar answered Nov 07 '22 06:11

eipi10