Skip to content

writeData converts character column to numeric value #264

@chicotobi

Description

@chicotobi

Describe the bug

Function "base::format" is used to convert a numeric value 1234.1 to a character "1234.1" in a data.frame using dplyr , writeData writes the string "1234.0999999999999". I don't fully understand what's happening. Maybe this is a problem of lazy evaluation.

The bug doesn't appear, if I use base::paste.

The bug doesn't appear, if the data.frame is bound to a variable and then written

To Reproduce

library(openxlsx)
library(magrittr)
library(dplyr)
library(XML)

fileName <- "test.xlsx"
wb <- createWorkbook()
sheet <- addWorksheet(wb,"Sheet")
data.frame(a=1234.1) %>% mutate(a=format(a)) %>% writeData(wb,sheet,.)
saveWorkbook(wb,fileName,overwrite=T)
unzip(fileName,exdir="tmp")
XML::xmlParse("tmp/xl/sharedStrings.xml")

Output

<?xml version="1.0" encoding="UTF-8" standalone="yes"?>
<sst xmlns="http://schemas.openxmlformats.org/spreadsheetml/2006/main" count="2" uniqueCount="2">
  <si>
    <t xml:space="preserve">a</t>
  </si>
  <si>
    <t xml:space="preserve">1234.0999999999999</t>
  </si>
</sst>

Expected behavior
String "1234.1" instead of a weird casted floating point number.

Additional context

This works:

library(openxlsx)
library(magrittr)
library(dplyr)
library(XML)

fileName <- "test.xlsx"
wb <- createWorkbook()
sheet <- addWorksheet(wb,"Sheet")
data.frame(a=1234.1) %>% mutate(a=paste(a)) %>% writeData(wb,sheet,.)
saveWorkbook(wb,fileName,overwrite=T)
unzip(fileName,exdir="tmp")
XML::xmlParse("tmp/xl/sharedStrings.xml")

This also works:

library(openxlsx)
library(magrittr)
library(dplyr)
library(XML)

fileName <- "test.xlsx"
wb <- createWorkbook()
sheet <- addWorksheet(wb,"Sheet")
df <- data.frame(a=1234.1) %>% mutate(a=format(a))
df %>% writeData(wb,sheet,.)
saveWorkbook(wb,fileName,overwrite=T)
unzip(fileName,exdir="tmp")
XML::xmlParse("tmp/xl/sharedStrings.xml")

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions