Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to read a .csv file containing apostrophes into R?

Tags:

r

csv

punctuation

I am having difficulty getting R to read a .txt or .csv file that contains apostrophes.

Some of my columns contain descriptive text, such as "Attends to customers' needs" or "Sheriff's deputy". My file opens correctly in Excel (that is, all the data appear in the correct cells; there are 3 columns and about 8000 rows, and there is no missing data). But when I ask R to read the file, this is what happens:

data <-read.table("datafile.csv", sep=",", header=TRUE)   Error in scan(file, what, nmax, sep, dec, quote, skip, nlines, na.strings,  :    line 520 did not have 3 elements 

(Line 520 is the first line that contains an apostrophe.)

If I go into the .txt or .csv file and manually remove all the apostrophes, then R reads the file correctly. However, I'd rather keep the apostrophes if I can.

I am new to R and would be grateful for any help.

like image 948
user1257313 Avatar asked Mar 08 '12 15:03

user1257313


People also ask

How do I read a CSV file in delimiter in R?

CSV file can be comma delimited or tab or any other delimiter specified by parameter "sep=". If the parameter "header=" is "TRUE", then the first row will be treated as the row names. read. csv(file, header = FALSE, sep = ",", quote = "\"", dec = ".", fill = TRUE, comment.

How do I read a CSV file in RStudio?

In RStudio, click on the Workspace tab, and then on “Import Dataset” -> “From text file”. A file browser will open up, locate the . csv file and click Open.

Which function is used for reading the .CSV file in R language?

csv() Function. read. csv() function in R Language is used to read “comma separated value” files. It imports data in the form of a data frame.


1 Answers

By default, read.table sees single and double quotes as quoting characters. You need to add quote="\"" to your read.table call. Or, you could just use read.csv, which only sees double quotes as quoting characters by default.

like image 189
Joshua Ulrich Avatar answered Sep 20 '22 13:09

Joshua Ulrich