Marco
Marco

Reputation: 9604

R: How to split a character string containing commas according to comma

Example

string <- "field1,field2,\"there is a , in field3\", field4, \"2,456\", field6"

A negative attempt:

test <- unlist(strsplit(noquote(string), ","))
test <- gsub("[^A-Za-z0-9' ']", "", test)
gsub("^\\s+|\\s+$", "", test)

[1] "field1"     "field2"     "there is a" "in field3" 
[5] "field4"     "2"          "456"        "field6"    

Note that fields containing commas are between \" ... \".

Upvotes: 1

Views: 1449

Answers (1)

gfgm
gfgm

Reputation: 3647

The read.table function will ignore commas inside quotation marks.

string <- "field1,field2,\"there is a , in field3\", field4, \"2,456\", field6"

desired_result <- read.table(text=string, sep=",")

Upvotes: 2

Related Questions