Characters converted to dates using write.csv

in my data frame there is column A with rows in character form

> df$A [1] "2-60", "2-61", "2-62", "2-63" etc 

I saved the table using write.csv, but when I open it using an Excel column, A will appear in date format:

 Feb-60 Feb-61 Feb-62 Feb-63 etc 

Does anyone know what I can do to avoid this?

I changed the write.csv arguments, but nothing worked, and I cannot find an example in Stack Overflow that helps solve this problem.

+5
source share
2 answers

Another solution is a bit tedious: use "Import Text File into Excel", click through the dialog boxes and in step 3 of 3 of the Import Text Wizard you can set the column data format, use "Text" for a column that has "2-60" , "2-61", "2-62", "2-63". If you use General (default), Excel tries to be smart and converts the answer for you.

+1
source

As stated in the comments, this is excel behavior, not R. And this cannot be deactivated:

Microsoft Excel is preprogrammed to make entering dates easier. For example, 12/2 changes before Dec 2. This is very unpleasant when you enter something that you do not want to change to a date. Unfortunately, there is no way to disable this . But there are ways around this.

Microsoft Office Article

The first proposed method around it, according to the article, does not help, since it depends on changing the formatting of the cell, but it is too late when you open the CSV file in excel (it is already converted to an integer representing the date)

However, there is some useful advice:

If you have only a few numbers to enter, you can stop Excel from changing them to dates by entering:

  • Apostrophe (') before entering a number, for example 11-53 or 1/47. Apostrophe does not appear in the cell after pressing Enter.

So, you can make the data display original using

 vec <- c("2-60", "2-61", "2-62", "2-63") vec <- paste0("'", vec) 

Just remember that the values ​​will still have an apostrophe if you read them again in R, so you might have to use

 vec <- sub("'", "", vec) 

It may not be perfect, but at least it works.

One option encloses the text in =" " as an excel formula, but has the same end result and uses more characters.

+7
source

All Articles