nicshah
nicshah

Reputation: 345

Use read.csv but keep the quote marks

I am trying to read in a csv file that has quote marks in it

 id, value, other
 1, "("a"="b", "b"="c", "c"="d")", 2
 2, "("a"="b", "b"="c", "c"="d")", 3

read.csv removes the quote marks so I end up with

 id, value, other
 1, (a=b, b=c, c=d), 2
 2, (a=b, b=c, c=d), 3

Anyone got a smart on how I can keep the quote marks?

Upvotes: 0

Views: 172

Answers (2)

TarJae
TarJae

Reputation: 79246

maybe this helps:

library(readr)

# simulating your data
id <- c(1,2)
value <- c('"("a"="b", "b"="c", "c"="d")"', '"("a"="b", "b"="c", "c"="d")"')
other <- c(2,3)

# creating a dataframe 
df <- data.frame(id, value, other)

# creating a csv file
write.csv(df,"mydata.csv", row.names = FALSE)

# Import csv dataset
mydata <- read_csv("mydata.csv")

# View data
View(mydata)

Upvotes: 0

Ronak Shah
Ronak Shah

Reputation: 389275

One way would be to change the separators.

We can change the separator to something else and using fread works.

data.table::fread(gsub(',(?![^\\(]*\\))', ';', text, perl = TRUE), quote = '')

#   id                         value other
#1:  1 "("a"="b", "b"="c", "c"="d")"     2
#2:  2 "("a"="b", "b"="c", "c"="d")"     3

regex for gsub has been taken from here to replace those commas that do not occur between ().

data

text = 'id, value, other
 1, "("a"="b", "b"="c", "c"="d")", 2
 2, "("a"="b", "b"="c", "c"="d")", 3'

Upvotes: 1

Related Questions