Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Exporting numeric vector as character to CSV

Let the following vectors:

x <- c(123456789123456789, 987654321987654321)
y <- as.character(x)

I'm trying to export y into a csv file for later conversion into XLSX (don't ask, client requested), like so:

 write.csv(y, file = 'y.csv', row.names = F)

If I open y.csv in a pure word processor, I can see it has correctly inserted quotes around the elements, but when I open it in Excel the program insists in converting the column into numbers and showing the contents in scientific format. This requires the extra step of reformatting the column, which can be a real time-waster when one works with lots of files.

How can I format a character vector of 20-digit numbers in R so that Excel doesn't display them in scientific notation?

like image 446
Waldir Leoncio Avatar asked Jun 28 '13 18:06

Waldir Leoncio


People also ask

How do I export a vector in R?

First of all, create a vector. Then, use write. csv function to save the vector in CSV file.

What is the R command that you can used to export a CSV file with headers?

Use write. csv() to export R DataFrame to CSV file with fields separated by comma delimiter, header (column names), rows index, and values surrounded with double-quotes.


2 Answers

Instead of opening the csv file via File->Open, you can go to Data->From Text in Excel and on the last step specify the Column data format to be Text.

Not really sure though that you save any time by doing this, you can also consider using the WriteXLS (or some other direct to xls) package.


edit

Here's a much better way of forcing Excel to read as text:

write.csv(paste0('"=""', y, '"""'), 'y.csv', row.names = F, quote = F)
like image 93
eddi Avatar answered Sep 28 '22 16:09

eddi


In Excel, select the column of numbers, and format them as text. (Format Cells -> Number tab -> Text in the list on the left)

like image 29
Hong Ooi Avatar answered Sep 28 '22 14:09

Hong Ooi