Cannot read unicode .csv into R

Ando Khachatryan picture Ando Khachatryan · May 30, 2013 · Viewed 24.7k times · Source

I have a .csv file, which contains the following data:

"Ա","Բ"
1,10
2,20

I cannot read it into R so that the column names are displayed like they are in the file.

d <- read.csv("./Data/1.csv", fileEncoding="UTF-8")
head(d)

Produces the following:

> d <- read.csv("./Data/1.csv", fileEncoding="UTF-8")
Warning messages:
1: In read.table(file = file, header = header, sep = sep, quote = quote,  :
  invalid input found on input connection './Data/1.csv'
2: In read.table(file = file, header = header, sep = sep, quote = quote,  :
  incomplete final line found by readTableHeader on './Data/1.csv'
> head(d)
[1] X.
<0 rows> (or 0-length row.names)

Meanwhile, doing the same without specifying the fileEncoding produces this:

> d <- read.csv("./Data/1.csv")
> head(d)
  Ô. Ô²
1  1 10
2  2 20

When I run the "file" utility to find out the encoding of the file, it says it is UTF-8:

Data\1.csv: UTF-8 Unicode text, with CRLF line terminators

I am using RStudio, Windows 7, R version 2.15.2, 32-bit.

Thanks in advance.

Answer

puslet88 picture puslet88 · Feb 11, 2015

I wrote a longer answer on the same issue here: R on Windows: character encoding hell .

Quick answer, using the parameter encoding instead of fileEncoding should fix your first issue. You will not be able to read it possibly in either console or table view in RStudio, but you will be able to use it in formulaes.

d <- read.csv("./Data/1.csv", encoding="UTF-8")
head(d)

Having saved your table into a UTF-8 file:

> test2 <- read.csv("test2.csv", header = FALSE, sep = ",", quote = "\"", dec = ".", fill = TRUE, comment.char = "", encoding = "UTF-8")
Warning message:
In read.table(file = file, header = header, sep = sep, quote = quote,  :
  incomplete final line found by readTableHeader on 'test2.csv'

This gives you how it looks like in the console and RStudio view

> test2
        V1       V2
1 <U+0531> <U+0532>
2        1       10
3        2       20

However importantly you are able to manipulate this within R. Thus in my case it is possible to see that the script window input Ա has UTF-8 encoding, and a grep correctly finds this encoding in your table.

> Encoding("Ա")
[1] "UTF-8"
> grep("Ա", as.character(test2[1,1]))
[1] 1

You may need to find suitable encoding variants that work on your settings, or possibly change them. Unfortunately I am not sure where it is done.

You might not be able to make it pretty in all stages, but it is definitely possible to get it to work also in Windows 7 environment.