“长”格式使用以下方式修改列list(unlist(...))
在“data.table”中,分配为:=
。因此,如果drop
使用时,您将拆分该列,然后将其删除!
我会尝试在文档中明确说明drop
仅适用于wide
格式,或添加message
如果用户尝试使用drop
以长格式。随意地提交 FR 或提交 PR https://github.com/mrdwab/splitstackshape/issues.
解决方法是分配另一列(例如“a_orig”),然后进行拆分:
jnk <- data.table(a=c('1,2,3,4,5','1,2,3','2,3'),b=c(5,4,3))
cSplit(jnk[, a_orig := a], "a", ",", "long")
# a b a_orig
# 1: 1 5 1,2,3,4,5
# 2: 2 5 1,2,3,4,5
# 3: 3 5 1,2,3,4,5
# 4: 4 5 1,2,3,4,5
# 5: 5 5 1,2,3,4,5
# 6: 1 4 1,2,3
# 7: 2 4 1,2,3
# 8: 3 4 1,2,3
# 9: 2 3 2,3
# 10: 3 3 2,3
我还没有进行广泛的测试,但可能的解决方法是:
cSplit2 <- function(indt, splitCols, sep = ",", direction = "wide",
fixed = TRUE, drop = TRUE, stripWhite = TRUE,
makeEqual = NULL, type.convert = TRUE) {
if (direction == "long" & !drop) {
indt <- as.data.table(indt)
indt[, `:=`(eval(paste(splitCols, "orig", sep = "_")),
lapply(splitCols, function(x) indt[[x]]))]
}
cSplit(indt, splitCols, sep, direction, fixed, drop, stripWhite,
makeEqual, type.convert)
}
基本思想是仅在以下情况下更改输入数据集:direction == "wide"
and drop = FALSE
。这与您的想法类似,但可以possibly是集成到实际包中的解决方案,在某个地方line 94 https://github.com/mrdwab/splitstackshape/blob/master/R/cSplit.R#L94。在这种情况下,只有indt[, `:=`(eval(paste(splitCols, "orig", sep = "_")), lapply(splitCols, function(x) indt[[x]]))]
部分应该是必要的。