R data.table中的变量值::与模式融合
回答时,我尝试将R data.table中的变量值::与模式融合,r,data.table,R,Data.table,回答时,我尝试将模式功能与数据一起使用。table::melt: df1 <- structure(list(Material_code = 111:112, actual_202009 = c(30L, 19L), actual_202010 = c(44L, 70L), actual_202011 = c(24L, 93L),
模式
功能与数据一起使用。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))
在变量
字段中,我想要的是“202009”而不是“1”
我完全知道我可以通过使用tstrsplit
实现这一目标:
melt(df1, 1)[,
c("type", "variable") := tstrsplit(variable, "_", fixed = TRUE)][,
dcast(.SD, Material_code + date ~ type)]
但是我希望通过模式
我可以产生一种不那么冗长的方式
我所尝试的:
- 我更改了
(默认值为true),但它在variable.factor=FALSE
列(1,2,…)中生成相同的值,只是这次它们是字符串variable
argument1
和argument2
):
是否可能,或者肯定要走很长的路?使用
数据。表1.14.1(自2021-05-18起的开发版本)可以使用新加入的测量功能来解决它。像这样:
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
检查?测量以及发布新闻以了解更多信息。似乎有一个分支(此处提到)可能会解决此问题,不确定其状态或时间线。相关:
melt(df1, 1, measure = patterns(actual = "actual_", pred = "pred_"), argument1, argument2)[1, ]
> Material_code variable actual pred
> 1: 111 202009 30 25
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