【发布时间】:2017-05-03 04:42:04
【问题描述】:
我有这个数据框
structure(list(rule.id = c(1, 2), rules = structure(1:2, .Label = c("Lamp1.1,Lamp1.2",
"Lamp2.1,Lamp2.2"), class = "factor")), .Names = c("rule.id",
"rules"), row.names = c(NA, -2L), class = "data.frame")
# rule.id rules
#1 1 Lamp1.1,Lamp1.2
#2 2 Lamp2.1,Lamp2.2
我需要用分隔符逗号(“,”)在“规则”列上拆分,出现多个逗号(不仅仅是示例中的 2 个),然后将其转换为规范化格式,同时保留相关的 rule.id 值来自原始df。 结果应如下所示:
structure(list(rule.id = c(1, 1, 2, 2), lhs = c("Lamp1.1", "Lamp1.2",
"Lamp2.1", "Lamp2.1")), .Names = c("rule.id", "lhs"), row.names = c(NA,
-4L), class = "data.frame")
# rule.id lhs
#1 1 Lamp1.1
#2 1 Lamp1.2
#3 2 Lamp2.1
#4 2 Lamp2.1
我有一个处理 str 拆分和规范化(长)格式的代码,但不知道如何处理 rule.id 要求
lhs.norm <- as.data.frame(
cbind(
rules.df$ruleid,
unlist(strsplit(
unlist(lapply(strsplit(unlist(lapply(as.character(rules.df$rules),function(x) substr(x,2,nchar(x)))), "} =>", fixed = T), function(x) x[1]))
,","))))
感谢@acrun 解决方案使用
cSplit(rules.df.lhs, "lhs", ",", "long"))
我对 1M 行进行了 19 秒的基准测试(结果约为 2M 行)
【问题讨论】: