当字段嵌入分隔符时,cSplit 不起作用

cSplit does not work when a field has embedded the separator

我正在使用 cSplit 将一列拆分为三个单独的列。分隔符是“/”

但是,我的其中一个字段嵌入了“/”分隔符。第三行的第三个元素应该是并在拆分后保持 "f/j"。

当我在下面的例子中尝试时,它创建了一个额外的(第四)列

name <- c("abc / efg / hij", "abc / abc / hij", "efg / efg / f/j", "abd / efj / hij")
y <- c(1,1.2,3.4, 5)

dt <- data.frame(name,y)
dt
dt <- cSplit(dt,"name","/", drop=FALSE)
dt

当我在超过 5,000 行的原始数据集中尝试它时,它会产生以下错误:

Error in fread(x, sep[i], header = FALSE):

Expecting 3 cols, but line 2307 contains text after processing all cols. Try again with fill=TRUE. Another reason could be that fread's logic in distinguishing one or more fields having embedded sep='/' and/or '\n' characters within unbalanced unescaped quotes has failed. If quote='' doesn't help, please file an issue to figure out if the logic could be improved.

如果数据的结构与您的 name 向量的结构相同,您可以使用以下内容,它依赖于目标 / 字符被空白字符包围的想法:

cSplit(dt,"name"," / ", drop=FALSE)

但是正如您所提到的,这导致了以下错误:

Error in fread(x, sep[i], header = FALSE) : 'sep' must be 'auto' or a single character

虽然我没有弄清楚主要原因,但我认为用下划线(或任何不同于 / 的其他字符)替换目标 / 字符,然后在下划线处拆分.以下可以作为例证:

dt$name <- gsub("([^/]+)/([^/]+)/(.*)", "\1_\2_\3", dt$name)
cSplit(dt, "name", "_", drop=F)

#           name   y name_1 name_2 name_3
# 1: abc_efg_hij 1.0    abc    efg    hij
# 2: abc_abc_hij 1.2    abc    abc    hij
# 3: efg_efg_f/j 3.4    efg    efg    f/j
# 4: abd_efj_hij 5.0    abd    efj    hij

希望对您有所帮助。

您应该可以设置 fixed = FALSE:

cSplit(dt, "name", " / ", fixed = FALSE, drop = FALSE)
##               name   y name_1 name_2 name_3
## 1: abc / efg / hij 1.0    abc    efg    hij
## 2: abc / abc / hij 1.2    abc    abc    hij
## 3: efg / efg / f/j 3.4    efg    efg    f/j
## 4: abd / efj / hij 5.0    abd    efj    hij