在回答这个问题patterns时,我尝试将该功能与以下内容一起使用data.table::melt:
df1 <- structure(list(Material_code = 111:112,
actual_202009 = c(30L, 19L),
actual_202010 = c(44L, 70L),
actual_202011 = c(24L, 93L),
pred_202009 = c(25L, 23L),
pred_202010 = c(52L, 68L),
pred_202011 = c(27L, 100L)),
class = c("data.table", "data.frame"),
row.names = c(NA, -2L))
Run Code Online (Sandbox Code Playgroud)
我想将宽表转换为长表,将actual和pred值分开。我认为日期部分将保留在变量中,但它被更改为因子数字(1、2 等):
melt(df1, 1, measure = patterns(actual = "actual_", pred = "pred_"))[1, ]
> Material_code variable actual pred
> 1: 111 1 30 25
Run Code Online (Sandbox Code Playgroud)
我想要该字段中的“202009”而不是“1” variable。
我完全意识到我可以通过使用以下方法来实现这一目标tstrsplit:
melt(df1, 1)[,
c("type", "variable") := tstrsplit(variable, "_", fixed = TRUE)][,
dcast(.SD, Material_code + date ~ type)]
Run Code Online (Sandbox Code Playgroud)
但我期待着patterns我可以产生一种不那么冗长的方式。
variable.factor = FALSE中生成相同的值,只是这次它们是字符串。variable我希望以下代码能够产生所示的输出(当然用适当的内容替换argument1and ):argument2
melt(df1, 1, measure = patterns(actual = "actual_", pred = "pred_"), argument1, argument2)[1, ]
> Material_code variable actual pred
> 1: 111 202009 30 25
Run Code Online (Sandbox Code Playgroud)
有可能吗,还是必须走很长的路?
在data.table1.14.1(开发版本截至 2021-05-18)中,可以使用新合并的measure函数来解决该问题。像这样:
melt(df1, measure.vars= measure(value.name, date, pattern="(actual|pred)_(.*)"))
Material_code date actual pred
1: 111 202009 30 25
2: 112 202009 19 23
3: 111 202010 44 52
4: 112 202010 70 68
5: 111 202011 24 27
6: 112 202011 93 100
Run Code Online (Sandbox Code Playgroud)
查看?measure发布新闻以获取更多信息。