1

Excel is adding a unicode character to a summary file I save from r as a .csv, where it adds "¬" in front of "±". Is there a way to edit the r script to prevent this?

cola <- c("a", "b", "c")
colb <- c("1", "2 ± 0.2", "3")
exampledf <- t(as.data.frame(rbind(cola, colb)))
write.csv(x = exampledf, file = "exampledf.csv", row.names = FALSE)

In R, this dataframe looks fine, but in excel it shows this:

cola    colb
a   1
b   2 ± 0.2
c   3
2
  • 3
    Maybe use an explicit argument for the fileEncoding parameter? See (eg) stackoverflow.com/questions/63754899/… Commented Nov 12 at 0:35
  • 1
    @TimWilliams readr::write_excel_csv from that link fixed it! Commented Nov 12 at 0:43

2 Answers 2

3

Reading ?write.csv, it mentions the fileEncoding= argument.

fileEncoding: character string: if non-empty declares the encoding to
          be used on a file (not a connection) so the character data
          can be re-encoded as they are written.  See file.

For windows-based compatibility, it is often useful to use "latin1". When we do that, it works.

write.csv(x = exampledf, file = "~/tmp/exampledf.csv", row.names = FALSE, 
          fileEncoding = "latin1")

screenshot of excel opening the CSV file with non-ascii characters shown correctly

PS: while I didn't see it at the time I wrote this, @TimWilliams had already recommended this approach in a comment. The answers in the link provided do not suggest "latin1" but more-so suggest the path towards resolution. Credit to Tim for thinking of it first :-)

Sign up to request clarification or add additional context in comments.

Comments

1

If you intend to use it with Excel, I think it is better to convert to .xlsx instead of .csv to avoid incompatibility.

if(!require("xlsx")){
    install.packages("xlsx")
}
xlsx::write.xlsx(x = exampledf, file = "exampledf.xlsx", row.names = FALSE)

That should do the trick.

3 Comments

Thanks! I tried readr::write_excel_csv just before you added this and it works too
FYI, the xlsx package has gone 5 years without a new release, and 3 years since a commit. There are several more recent (and actively maintained) packages for writing .xlsx files, including (in no particular order) writexl, openxlsx, and openxlsx2, perhaps more, and none of these require rJava, which while once setup correctly it works fine, it is a lot of overhead and can cause problems that are at times rather difficult to decipher.
Noted. Thanks a lot.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.