1

Suppose I use the xlsx package to write a dataframe from r to excel. And suppose I have a dataframe with a column title that includes a question mark (code below):

library(xlsx)
rm(list = ls())

fpath <- "whatever filepath"

#My df
df <- data.frame("Questions?" = c("bla", "bla bla"), "123Numbers"= c(1,2))

#Now output 
wb <- createWorkbook()
sh <- createSheet(wb, sheetName = "Bla")
addDataFrame(df, sh)

saveWorkbook(wb, paste0(fpath,".xlsx"))

When I open the excel output file, I get the following: Result

  1. Why does the question mark show up as a period in the Questions column title?
  2. Why is there a random "X" character in front of the 123Numbers column title?

Of course, if there is an easy fix to this that I am missing, please advise. Thanks!

Nana
  • 13
  • 2
  • 4
    You can use `check.names = FALSE` in `data.frame` i.e. `df <- data.frame("Questions?" = c("bla", "bla bla"), "123Numbers"= c(1,2), check.names = FALSE)` – akrun Jan 07 '20 at 20:05
  • 1
    works perfectly. I never used check.names before so I'll look that up, thank you so much! – Nana Jan 07 '20 at 20:15

1 Answers1

0

The check.names argument is by default TRUE in data.frame and it would make sure that all the non-standard column names are modified by applied (make.names-> make.unique). If we specify it as FALSE, the column names would not get changed

df <- data.frame("Questions?" = c("bla", "bla bla"),
    "123Numbers"= c(1,2), check.names = FALSE)
akrun
  • 874,273
  • 37
  • 540
  • 662