【问题标题】:R: How to split a character string containing commas according to commaR:如何根据逗号拆分包含逗号的字符串
【发布时间】:2016-11-29 14:15:07
【问题描述】:

例子

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

消极的尝试:

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"    

请注意,包含逗号的字段介于 \" ... \" 之间。

【问题讨论】:

  • 你的理想结果是什么?
  • 试试 read.table(text=string, sep=",")。它将忽略引号内的逗号。它适用于您的示例。
  • 我喜欢简单的答案 :-) 如果您将其转换为答案,我会接受!谢谢!
  • 感谢您的提议,我很喜欢 stackoverflow 的游戏化建议。

标签: r split character


【解决方案1】:

read.table 函数将忽略引号内的逗号。

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

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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-06-11
    • 2016-05-28
    • 1970-01-01
    • 2020-01-03
    • 2015-03-07
    • 1970-01-01
    相关资源
    最近更新 更多