Marco Marco - 5 days ago 5
R Question

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
\" ... \"
.

Answer

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=",")
Comments